My app takes a photo using the Camera and saves it like this C:\Users...\Pictures\file.PNG. I have an object with string "C:\Users\...\Pictures\file.PNG" and binding set to that string, but it does not load the Image. If i place the image to Assets and set the string to "Assets\file.png" it works. Is it possible to bind outside of Assets?
First of all you need to realize that you do not have access to file system as e.g. in Win32 apps. So the full path in UWP app is not relevant anymore. Please take a look on this link to explain it more and nice one here.
I assume you're using Image control to display image. Something like:
MainPage.xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Loaded="MainPage_OnLoaded">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image Name="Img1" />
</Grid>
</Page>
MainPage.xaml.cs
private async void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
var file = await Windows.Storage.KnownFolders.CameraRoll.GetFileAsync("p1.png");
using (var imgStream = await file.OpenStreamForReadAsync())
{
var bitmapImg = new BitmapImage();
bitmapImg.SetSource(imgStream.AsRandomAccessStream());
Img1.Height = bitmapImg.PixelHeight; //Need to take care of proper image-scaling here
Img1.Width = bitmapImg.PixelWidth; //Need to take care of proper image-scaling here
Img1.Source = bitmapImg;
}
}
When you understand file-access concept files in UWP, you can take closer look on built-in camera control support. There's also example how to directly access captured image without hassling with file names.
My application has a lot of windows and most of them share some basic features. Because of that I extended the Window class to create a base for all my windows.
Everything compiles and displays fine but the designer just shows an empty window when I use my window class.
I made a basic example that can be easily used, my real window is much more complex but this shows the problem.
Here is the code:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
namespace WpfApplication1
{
[ContentProperty("ContentElement")]
public class MyWindow : Window
{
public ToolBar ToolBar { get; private set; }
public StatusBar StatusBar { get; private set; }
public Border ContentBorder { get; private set; }
public UIElement ContentElement
{
get { return (UIElement)GetValue(ContentElementProperty); }
set { SetValue(ContentElementProperty, value); }
}
public static readonly DependencyProperty ContentElementProperty = DependencyProperty.Register(
"ContentElement", typeof(UIElement), typeof(MyWindow),
new PropertyMetadata(null, (d, e) =>
{
MyWindow w = (MyWindow)d;
w.ContentBorder.Child = (UIElement)e.NewValue;
}));
public MyWindow() : base()
{
ToolBar = new ToolBar();
ToolBar.Height = 30;
ToolBar.VerticalAlignment = VerticalAlignment.Top;
StatusBar = new StatusBar();
StatusBar.Height = 20;
StatusBar.VerticalAlignment = VerticalAlignment.Bottom;
ContentBorder = new Border();
ContentBorder.SetValue(MarginProperty, new Thickness(0, 30, 0, 20));
Grid grid = new Grid();
grid.Children.Add(ToolBar);
grid.Children.Add(ContentBorder);
grid.Children.Add(StatusBar);
Content = grid;
}
}
}
XAML example for using MyWindow:
<local:MyWindow x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300">
<Grid>
<Rectangle Fill="Blue" />
</Grid>
</local:MyWindow>
Doing the exact same thing with a UserControl works just fine, also in the designer. Just replace every occurance of MyWindow with MyUserControl and extend from UserControl if you want to try that.
Is there any way I can get a custom Window like that to work with the designer, or do i have to make a UserControl and use that in every window?
Also, is this some kind of bug or intended behavior?
Addional info: I'm running Visual Studio 2015 Community and I'm using .net 4.6
I Also tried another approach. Instead of using the ContentPropertyAttribute i have overwritten the ContentProperty like this:
new public object Content {
get { return GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
new public static DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(BaseUserControl), new PropertyMetadata(null, (s, e) =>
{
MyWindow bw = (MyWindow)s;
bw.ContentBorder.Child = (UIElement)e.NewValue;
}));
Again this works completely fine with a UserControl. With a Window I can at least see the Content in the designer now, but the ToolBar and StatusBar are still not showing up in the designer. When running it everything works correctly.
First, I am no super expert on WPF, but have done a bunch and think I can offer and help clarify some components. First, you can NOT derive from a .XAML based declaration of a WPF-Window, it can only be if entirely within code. I have come to find that sometimes the visual element building is much easier to do in XAML than it is within code, but both can and do work.
So, that said, I would like to offer a solution that might work for you. Starting with WPF Window Style / Templatea, if you are not already familiar with them, along with other controls you can run through their defaults.
First, I am starting with a RESOURCE DICTIONARY STYLE definition that will mimic much of what you may want in your default form. This becomes the stuff within the "ControlTemplate" of the style definition. I have created this as a file "MyWindowStyle.xaml" at the root level WpfApplication1 I created on my machine (just to match your sample project file namespace reference).
Inside the template, you could have almost anything... grids, dock panel, stack panels, etc. In this case, I have used a DockPanel and added your sample ToolBar, StatusBar and two extra labels just for sample. I also preset size and bogus color just to give visualization of the parts when you confirm their impact.
The CRITICAL element to look at is the . This identifies where the content for each of your DERIVED Windows content will be placed... Think of it as a place-holder for each one of your forms for individuality while the rest of the form, its controls all remain consistent. You will see it come into play as you play around with it.
The content of it is and notice the style x:Key="MyWindowStyle". This coincidentally is the same as the xaml, but you could have 100's of styles within a single resource dictionary. I am keeping simple to just the one for demo purposes.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Style x:Key="MyWindowStyle" TargetType="Window">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Grid>
<Grid.Background>
<SolidColorBrush Color="{DynamicResource WindowColor}"/>
</Grid.Background>
<AdornerDecorator>
<DockPanel LastChildFill="True" Background="Blue">
<!-- List items docked to the top based on top-most first going down -->
<ToolBar x:Name="tmpToolBar" Height="45" DockPanel.Dock="Top" />
<Label Content="Testing by Style"
Height="30" Width="150" DockPanel.Dock="Top"/>
<!-- When docking to the bottom, start with bottom most working up -->
<StatusBar x:Name="tmpStatusBar" Height="30"
Background="Yellow" DockPanel.Dock="Bottom" />
<Label Content="Footer area based from style"
Height="30" Width="250" DockPanel.Dock="Bottom" />
<!-- This one, since docked last is rest of the space of the window -->
<ContentPresenter DockPanel.Dock="Bottom"/>
</DockPanel>
</AdornerDecorator>
<ResizeGrip x:Name="WindowResizeGrip"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Visibility="Collapsed"
IsTabStop="false" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="ResizeMode" Value="CanResizeWithGrip">
<Setter TargetName="WindowResizeGrip"
Property="Visibility" Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Next, we need to make this publicly available for the entire duration of the application, including availability within the designer mode... Within your projects "App.xaml" which is the startup for the application, it will have a default and empty area. Replace it with this.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/WpfApplication1;component/MyWindowStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now, to a CODE-ONLY (not a .xaml window based definition) of your "MyWindow.cs" class. If you look at the style where I declared the toolbar and statusbar, I assigned them the names of "tmpToolBar" and "tmpStatusBar" respectively. Notice the [TemplatePart()] declarations. I am now expecting the template to HAVE these controls by the given name within the TEMPLATE somewhere.
Within the constructor, I am loading the Style from the App.xaml resource dictionary being fully available. Then I follow-up with the OnApplyTemplate() which I typically heavily document my code so anyone following me has some idea how / where things originated from and self explanatory.
My entire "MyClass.cs" is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace WpfApplication1
{
[TemplatePart(Name = "tmpToolBar", Type = typeof(ToolBar))]
[TemplatePart(Name = "tmpStatusBar", Type = typeof(StatusBar))]
public class MyWindow : Window
{
protected ToolBar myToolBar;
protected StatusBar myStatusBar;
public MyWindow() : base()
{
// NOW, look for the resource of "MyWindowStyle" within the dictionary
var tryStyle = FindResource("MyWindowStyle") as Style;
// if a valid find and it IS of type Style, set the style of
// the form to this pre-defined format and all it's content
if (tryStyle is Style)
Style = tryStyle;
}
// the actual template is not applied until some time after initialization.
// at that point, we can then look to grab object references to the controls
// you have need to "hook up" to.
public override void OnApplyTemplate()
{
// first allow default to happen
base.OnApplyTemplate();
// while we get the style loaded, we can now look at the expected template "parts"
// as declared at the top of this class. Specifically looking for the TEMPLATE
// declaration by the name "tmpToolBar" and "tmpStatusBar" respectively.
// get object pointer to the template as defined in the style template
// Now, store those object references into YOUR Window object reference of Toolbar
var myToolBar = Template.FindName("tmpToolBar", this) as ToolBar;
if (myToolBar != null)
// if you wanted to add your own hooks to the toolbar control
// that is declared in the template
myToolBar.PreviewMouseDoubleClick += myToolBar_PreviewMouseDoubleClick;
// get object pointer to the template as defined in the style template
var myStatusBar = Template.FindName("tmpStatusBar", this) as StatusBar;
if (myStatusBar != null)
myStatusBar.MouseDoubleClick += myStatusBar_MouseDoubleClick;
// Now, you can do whatever else you need with these controls downstream to the
// rest of your derived window controls
}
void myToolBar_PreviewMouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// in case you wanted to do something based on PreviewMouseDoubleClick of the toolbar
MessageBox.Show("ToolBar: Current Window Class: " + this.ToString());
}
void myStatusBar_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// in case something for MouseDoubleClick on the StatusBar
MessageBox.Show("StatusBar: Current Window Class: " + this.ToString());
}
}
}
So now, lets put it into place. Have your application's main window derive from the MyWindow class. The only thing you need there is
namespace WpfApplication1
{
public partial class MainWindow : MyWindow
{}
}
In the DESIGNER of your form, put in a few controls, such as label, textbox, whatever. You do not see your actual other style yet, but just go with it. Save and run the sample app. Your main window should be displayed with the entire pre-defined template there ALONG WITH the few extra control you had placed specifically on this form.
Now, to get the full visualization in your "MainWindow" from the designer perspective. Within the .xaml area of
<my:MyWindow
x:Class="WpfApplication1.MainWindow"
[other declarations] >
just add the following before the close ">"
Style="{StaticResource MyWindowStyle}"
The resource is available via the App.xaml at startup and you should now be able to see the entire visual while you are designing... but you cant change the outermost template, just the content specific to this one page as mentioned about the "ContentPresenter" part of the template definition. What you are changing is within the place-holder portion allocated by the Template. If you want to change the main part of the window controls, you need to update the TEMPLATE!
But here is part of the trick of the template designer. Start with this, and build in what you need visually, get it placed right and once ready, take it out of here and put into the template and now it is applicable to the rest of all windows. Fix fonts, sizes, colors, whatever.
Hope this helps, and if you have any questions for follow-up, let me know.
Window class is very complex in compare to UserControl class. Microsoft has written more than 8k lines of code in Window class compare to 80 lines in UserControl, additionally Window class contain many operation/event/restriction on content property, and any one piece of code is hindering in rendering the content when you use [ContentProperty("ContentElement")] with the Window subclass MyWindow .
Probably making it a UserControl is better option, If not possible you can write some code temporarily(copy code from ContentElement property) in content property to see the design view.
<lib:MyWindow.Content>
<Button Content="Click" Width="200" />
</lib:MyWindow.Content>
and then just remove the code before run time. (Not a good idea but, whatever works.:) and I suspect that you have already figured that out.
I need to embed a standard webapp inside a windows app container.
The container just needs to be a wrapper around a webkit or similar rendering engine (I would like to avoid using IE rendering engine if possible) and it would contain some minimal window management logic - things like being borderless with no titlebars, being able to fix position and size, and custom overlay/always-on-top rules based on currently focused window.
I've been looking at node-webkit and it seems to fit the bill as far as containing a webapp is concerned, but I'm not sure I would be able to do the latter.
Can this be done with node-webkit, is there some other approach that would fit my use case better? I have absolutely no idea how windows app development is done, so I would appreciate some help.
If you are using WPF, you can create you window with something like this (xaml):
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="None"
Title="MainWindow" Left="100" Top="200" Height="350" Width="525" PreviewKeyDown="Window_PreviewKeyDown">
<Grid x:Name="grdBrowserHost">
</Grid>
</Window>
WindowStyle attr None means "borderless with no titlebars" window. Left and Top are for position, and Width and Height are self-explanatory. All those properties can be accessed via code-behind with simple this.Width, etc... PreviewKeyDown I put here because in this example (as you will see), Topmost property will be changed from code behind (dynamically).
Code-behind should look something like
using System;
using System.Windows;
using System.Windows.Input;
namespace WpfApplication2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
System.Windows.Controls.WebBrowser browser = new System.Windows.Controls.WebBrowser();
// you can put any other uri here, or better make browser field and navigate to desired uri on some event
browser.Navigate(new Uri("http://www.blic.rs/"));
grdBrowserHost.Children.Add(browser);
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
this.Close();
}
else
{
this.Topmost = !this.Topmost;
}
}
}
}
In this example I have created default WebBrowser control for showing html. If you want some other web rendering engine you must find 3rd-part control and include it in your references. For webkit, you can check How to use WebKit browser control in WPF
What you need is "UWP Bridge for web apps" ;-)
Look in the Windows Dev Center:
UWP Bridge for web apps - Create your app now
First of all, I work in C# / XAML on Visual Studio C# 2013 Express.
I write today for a swf player in a wpf application. I read many discuss on this subjetcs but no one can solve my problem. I use a PageSwitcher, each page inherit from UserControl class and I create a button for each .swf file in a directory. This work fine. When I click on one of them, I want to open a new page wich is the swf viewer. I can open a new page, but my pdf viewer not work. I tried many ways to resolve my problem, but nothing work. I have a WinForm application wich do what I want, but I can't add it in my WPF application I try a WindowsFormHost but I still have the same error : Type or namespace 'AxShockwaveFlashObjects' not found, whereas I add AxInterop.ShockwaveFlashObjects.dll and/or Interop.ShockwaveFlashObjects.dll
Here is my code :
XAML
<UserControl x:Class="WPFPageSwitch.swf"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
mc:Ignorable="d">
<Grid x:Name="Container">
</Grid>
</UserControl>
C#
namespace WPFPageSwitch
{
public partial class swf : System.Windows.Controls.UserControl, ISwitchable
{
public swf(string swf)
{
InitializeComponent();
System.Windows.Forms.Integration.WindowsFormsHost swfPlayer = new System.Windows.Forms.Integration.WindowsFormsHost();
AxShockwaveFlashObjects.AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlashObjects.AxShockwaveFlash();
swfPlayer.Child = axShockwaveFlash;
Container.Children.Add(swfPlayer);
}
}
}
Somebody can help me ?
The error is here : AxShockwaveFlashObjects.AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlashObjects.AxShockwaveFlash();
Add a reference to it.
AxShockwaveFlashObjects is a COM library to allow you to integrate Flash content into your .NET application. Demo Here
I'm trying to put together a simple Windows 8 metro style app in c# with tile notifications but I can't seem to get them working.
What I can't quite figure out yet is where the code to update the tile notifications should reside. I've had a look at the Javascript sample, but I'm not seeing how that works in a C# app. Has anyone got some sample code or a quick tip on where tile updates should happen in a C# metro app?
My understanding is that every app decides where to do this for itself. Normally, you'd do it whenever you're also updating your normal UI with the same data - e.g. if your app is an RSS reader, and you've just downloaded a new item to display, that's where you also update your tile by posting a notification. In the sample JavaScript app, this is done from event handlers for controls for the sake of convenience.
As for the code to change the tile, it should be almost identical to JavaScript version, since in both cases you use Windows.UI.Notifications namespace. Following is a very simple C# app that updates the tile when you click the button. XAML:
<UserControl x:Class="TileNotificationCS.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
d:DesignHeight="768" d:DesignWidth="1366">
<StackPanel x:Name="LayoutRoot" Background="#FF0C0C0C">
<TextBox x:Name="message"/>
<Button x:Name="changeTile" Content="Change Tile" Click="changeTile_Click" />
</StackPanel>
</UserControl>
and code behind:
using System;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
namespace TileNotificationCS
{
partial class MainPage
{
TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
public MainPage()
{
InitializeComponent();
}
private void changeTile_Click(object sender, RoutedEventArgs e)
{
XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText01);
XmlElement textElement = (XmlElement)tileXml.GetElementsByTagName("text")[0];
textElement.AppendChild(tileXml.CreateTextNode(message.Text));
tileUpdater.Update(new TileNotification(tileXml));
}
}
}
Don't forget that you need a wide tile for text to show up - to get it, set some image for "Wide Logo" in Package.appxmanifest.
Make sure you change the Initial rotation to Landscape, set some image for Widelogo, and use this method to set the text along with an expiry.
void SendTileTextNotification(string text, int secondsExpire)
{
// Get a filled in version of the template by using getTemplateContent
var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText03);
// You will need to look at the template documentation to know how many text fields a particular template has
// get the text attributes for this template and fill them in
var tileAttributes = tileXml.GetElementsByTagName("text");
tileAttributes[0].AppendChild(tileXml.CreateTextNode(text));
// create the notification from the XML
var tileNotification = new TileNotification(tileXml);
// send the notification to the app's default tile
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}
Here is a detailed explanation http://www.amazedsaint.com/2011/09/hellotiles-simple-c-xaml-application.html