I have custom ContentControl
public class MyContentControl: ContentControl
{....}
with Content defined in XAML like this
<controls:MyContentControl x:Name="myContentControl">
<controls:MyContentControl.Content>
<controls:UserControl1 />
</controls:MyContentControl.Content>
</controls:MyContentControl>
Content shows in designer and in the device when I launch my application. But when I try to change Content property programmatically, for example
UserControl2 control2 = new UserControl2();
myContentControl.Content = control2;
MyContentControl shows nothing. Using standard ContentControl give the same result.
Any suggestions are welcome.
I followed your code to make simple code sample to test. There's no problem.
public class CustomContentControl:ContentControl
{//......}
<Grid>
<local:CustomContentControl x:Name="content">
</local:CustomContentControl>
</Grid>
MyUserControl1 myUserControl1 = new MyUserControl1();
content.Content = myUserControl1;
<UserControl
x:Class="AppContent.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppContent"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<TextBox Text="abc"></TextBox>
</Grid>
You might have done some specific settings in your code. #Martin Zikmund's suggestion also was reasonable. You could refer to his suggestion and check your code. After that, if you still could not solve this issue, please provide a Minimal, Complete, and Verifiable example.
This should work. The reason could be that the control does not stretch and is displayed just 0x0 in size. Try to set absolute Width and Height to the control2 and check if it displays. You can also set myContentControl.HorizontalContentStretch and myContentControl.VerticalContentStretch.
You can try running the app in debugger and then use the Live Property Explorer to see what the actual size of the control inside Content is.
Ok, I found out where the things went wrong. I am using different controls for desktop and mobile devices, so I put some of theirs XAML views to the DeviceFamily-Mobile folder. This way they automatically use when needed. I've confused namespaces, because all XAML views in this folder have a root namespace for accessibility reasons. When I was trying to add control to the ContentControl via c#, I didn't resolve namespace where my controls were placed. So I've put XAML view as a childs to the ContentControl, and they staying invisible as none of them has InitializeComponent() method. Adding correct controls with initialization fixed my problem.
I am very grateful for your answers, they pointed me to the right way.
I've been researching all over the internet for a way to change the pushpin image in the Bing Maps C# control. The closest that I came was using the following solution:
Change image for pushpin WPF
It is not entirely what I'm looking for, as I want to be able to change the color of the push pin as well as add a label.
The above solution is basically an image that is drawn over a push pin without additional functionality such as adding a label. I want to be able to easily change an image while having custom label functionality.
Is there any other way of doing this? An alternative would be to make use of "standard" Bing push pin graphics and be able to change the size. However it seems this functionality is not available in the C# control
This following blog post answers my questions:
http://dennis.bloggingabout.net/2012/10/17/bing-maps-on-wpf-and-custom-pushpin-tutorial-for-pixelsense/
Surprisingly this is the only question about this topic in SOF (the other one is closed). To complete newbies in WPF (like me) it is hard to find good and at the same time simple information, so I will show how I managed to use custom images in programatically added pushpins in VB.NET:
This is my MainWindow.xaml file:
<Window x:Class="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:m="clr-namespace:Microsoft.Maps.MapControl.WPF;assembly=Microsoft.Maps.MapControl.WPF"
xmlns:local="clr-namespace:MyBingMapsApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="PushpinControlTemplate" TargetType="m:Pushpin">
<Grid>
<Rectangle Width="24" Height="24">
<Rectangle.Fill>
<ImageBrush ImageSource= "Resources/marker_green.png"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</ControlTemplate>
</Window.Resources>
<Grid>
<m:Map x:Name="myMap"
CredentialsProvider= "xxxxxx mycredentialskey xxxxxxxx"
Center="42.13618,-0.40822"
ZoomLevel="15">
</m:Map>
</Grid>
</Window>
As you can see, you must define a ControlTemplate whose TargetType="m:Pushpin"
There you can draw whatever you need. The simplest: use an image from your resources.
Important: change image "Build action" to Resource (click on the image in your resources folder of the Solution Explorer and change it in Advanced settings). Otherwise you will have to hardwrite the image path or use Uris or more complicated stuff
Now you are ready to create a pushpin wherever you need and assign your template:
mypin = New Pushpin
mypin.Location = New Location(mylat, mylon)
mypin.ToolTip = "This is a pushpin with custom image"
Dim mytemplate As System.Windows.Controls.ControlTemplate = FindResource(“PushpinControlTemplate”) 'here of course you must put the key name of your template
mypin.Template = mytemplate
I am trying to display an image on a WPF page. The code is shown below:
<Grid>
<TextBlock Margin="32,332,395,74" Cursor="None">
Click to <Hyperlink NavigateUri="TestWindow.xaml">sign a document</Hyperlink>
</TextBlock>
<Image HorizontalAlignment="Left" Height="151" Margin="32,96,0,0" VerticalAlignment="Top" Width="179"
Source="signature.png" Visibility="Visible" Name="signImage"/>
The problem is the image shows in WPF designer but when I run the program, the image does not display on the page.
Note the image is displayed on a PAGE not a WINDOW
Another option is to use a resource, e.g. in your app.xaml:
<Application.Resources>
<BitmapImage x:Key="signatureSrc" UriSource="/MyProject;component/ImageFolderIfThereIsOne/signature.png" />
</Application.Resources>
and use it like this
<Image Height="100" VerticalAlignment="Top" Width="100" Source="{StaticResource signatureSrc}" />
Try this out PackURIs
Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;
The URI is broken out into parts:
Authority: application:///
Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path
AssemblyShortName: the short name for the referenced assembly.
;Version [optional]: the version of the referenced assembly that
contains the resource file. This is used when two or more referenced
assemblies with the same short name are loaded.
;PublicKey [optional]: the public key that was used to sign the
referenced assembly. This is used when two or more referenced
assemblies with the same short name are loaded.
;component: specifies that the assembly being referred to is
referenced from the local assembly.
/Path: the name of the resource file, including its path, relative to
the root of the referenced assembly's project folder.
The three slashes after application: have to be replaced with commas:
Note: The authority component of a pack URI is an embedded URI that
points to a package and must conform to RFC 2396. Additionally, the
"/" character must be replaced with the "," character, and reserved
characters such as "%" and "?" must be escaped. See the OPC for
details.
And of course, make sure you set the build action on your image to Resource.
Frustrated with this myself, I just figured out the the page uses a relative location for the image. In my case, the image was in the folder "Graphics/logo.jpg", and the page was in the folder "View/Setting/About". I updated the Source of the image to ../../Graphics/logo.jpg and it worked.
I have two .png files added to my resources which I need to access their Uri when doing binding.
My xaml code is as followed:
<Grid>
<Image>
<Image.Source>
<BitmapImage DecodePixelWidth="10" UriSource="{Binding Path=ImagePath}"/>
</Image.Source>
</Image>
</Grid>
and the binding code using ImagePath is:
ImagePath = resultInBinary.StartsWith("1") ? Properties.Resources.LedGreen : Properties.Resources.ledRed;
However
Properties.Resources.LedGreen
returns a Bitmap instead of String containing the Uri of that particular image.
I just want to know how to extract that value without a need to address a path of the image in the directory that it's stored. (Which honestly I am not sure is a right thing to do as I couldn't find any similar situation on the net).
Please let me know if there is even a preferred method to the one I am trying to use if available.
In a WPF application you would usually not store images in Properties/Resources.resx and access them by means of the Properties.Resources class.
Instead you just add the image files to your Visual Studio project as regular files, perhaps in a folder named "Images" or the like. Then you would set their Build Action to Resource, which is done in the Properties window. You get there e.g. by right-clicking the image file and select the Properties menu item. Note that the default value of the Build Action should be Resource for image files anyways.
In order to access these image resources from code you would then use a Pack URI. With the above folder name "Images" and an image file named "LedGreen.png", creating such an URI would look like this:
var uri = new Uri("pack://application:,,,/Images/LedGreen.png");
So you could perhaps declare your property to be of type Uri:
public Uri ImageUri { get; set; } // omitted INotifyPropertyChanged implementation
and set it like this:
ImageUri = resultInBinary.StartsWith("1")
? new Uri("pack://application:,,,/Images/LedGreen.png")
: new Uri("pack://application:,,,/Images/LedRed.png");
Finally your XAML should look like shown below, which relies on built-in type conversion from Uri to ImageSource:
<Grid>
<Image Width="10" Source="{Binding Path=ImageUri}" />
</Grid>
Declare the Properties.Resources.LedGreen property as ImageSource and set it to Uri location rather than the Bitmap object.
Or if you insist of storing it as a bitmap you can get the source by returning Properties.Resources.LedGreen.ImageSource which will be of type ImageSource.
I would prefer the first approach.
The exception in the title is thrown when I open a window in WPF, the strange thing is that this does not happen on my Windows 7 development machine nor does it happen when it is deployed on Windows 7.
I only get this error on Windows XP, and only the second time that I open the window.
Here is the code to open the window:
ReportParametersWindow win = null;
bool canOverWrite = _shownReports.Contains(rpt.FriendlyName);
if (!(canOverWrite))
win = new ReportParametersWindow(rpt.FriendlyName, rpt.ReportParameters, canOverWrite);
else
win = new ReportParametersWindow(rpt.FriendlyName, (container.ParametersWindow as ReportParametersWindow).Controls, canOverWrite);
win.ShowDialog();
And the XAML for the window:
<Window xmlns:my="clr-namespace:MHA.Modules.Core.Controls;assembly=MHA.Modules.Core"
x:Class="MHA.Modules.Reports.Views.ReportParametersWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Parameters" Height="500" Width="600" MinWidth="500" MaxHeight="500"
Icon="/MHA.Modules.Reports;component/Images/Parameters.ico" SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen"
xmlns:odc="clr-namespace:Odyssey.Controls;assembly=Odyssey" Closed="Window_Closed">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" Name="ScrollViewer1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" CanContentScroll="True">
<StackPanel Name="ParameterStack">
<my:LocationCtl Text="Parameters for report - " Name="loc"/>
</StackPanel>
</ScrollViewer>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox ToolTip="This will replace the first report of the same type that was shown." Name="chkOverwrite" Content="Overwrite old" VerticalAlignment="Center" Margin="5,0"></CheckBox>
<Button Grid.Column="2" HorizontalAlignment="Right" Margin="5,0" Height="30" Style="{StaticResource DionysusButton}" Width="100" IsDefault="True" Click="Button_Click">
<StackPanel Orientation="Horizontal">
<Image Source="/MHA.Modules.Reports;component/Images/Success.png"></Image>
<TextBlock Margin="5,0" Text="Accept" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</Button>
</Grid>
</Grid>
Does anyone have suggestions?
The solution is quite a weird one but I have it figured out.
I realized that the error was occurring on the InitializeComponent() of the window, I then added a try catch to the constructor and showed the InnerException of the Exception.
The error that I received is "Image format not recognized".
I have no idea why this happens only on XP and the second time that the window is shown but by replacing my .ico with a .png the problem was resolved.
Hope this helps someone.
I just ran into this issue as well... I know this is old, but what I had to end up doing was set the images to Resource, and Copy Always... only by browsing my /bin/Debug folder did I realize that the images were not at a valid path location
This problem can also occur if the required image is not available at the specified location. So Check the inner exception and add any image that might have been missed or misspelled.
I got this error because my Command Binding of a Button was wrong:
<Button Command="MyCommand" />
instead of
<Button Command="{Binding MyCommand}" />
You Should first Import Image to your project
Solution Explorer - Show All
then Right Click on the image and select Include
Now Use
end
In my case the root cause was wrong BuildAction property on all images. I fixed it by changing BuildAction from Content to Resource.
I got this exception after moving my Resource Dictionary from root of my application to a subdirectory. In my case the problem were Image paths inside my Style setters inside the dictionary. After I preceded them with a forward slash '/', the application started to work again. If you're having a similar problem, open the resource dictionary, and the error will be highlighted with the blue 'squiggly' line.
In my case, I have added 'WpfToolkit' refrence to my module, and there is no need.
After deleting this reference, everything was ok. Strange!
Just go to Project>[Your Project Name] Settings and set your .ico file as icon now your .ico file is mentioned in your manifest file and you can simply include your .ico file in your XAML file using
Icon="[icon file name].ico"
<Window x:Class="[Your project's name].MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="" Height="500" Width="720"
Icon="[your icon's name].ico">
In my case, I found the mew added icon(image) file is not added into my project. It is resolved after I added these new image files into my project, not just file copy.
In my case the files existed on disk but were not referenced in the project. I added them to the project but the error persisted despite reloading the solution and restarting Visual Studio.
I changed the references to an existing file that was already in the project and it ran fine (albeit with the wrong graphic). I then changed it back to the original reference and it ran fine again but with the correct image. Presumably the error was getting cached somehow until it was flushed out of the system...
Remove the "WPFToolkit" reference from your cs.proj file.
<Reference Include="WPFToolkit, Version=3.5.40128.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
It should do the trick.
copy and paste the file name is changed. that's why I get this error.
well, in my case I added the new photos to the image Folder in FileExplore while image folder was added to the project while ago. and there wasn't any problem with the image path in the project. but when I build the project I face to the same error.
then I add those new photos to project by right click on the image folder and add the existing item and selected new photos. then I cleaned the solution and build it again.
There are many ways to cause this issue. Since the exception isn't specific. Here is a list of solutions to try from this thread.
Firstly, you can try/catch the InitializeComponent() call which is throwing the exception to get more details about what happened.
If the image is an icon (.ico) file use an image (.png) or equivalent instead
In some cases .ico files are problematic - I was using .NETCore
Make sure your image file has a build action of Resource or Embedded Resource
The resource files described in this section are different than the
resource files described in XAML Resources and different than the embedded
or linked resources described in Manage Application Resources (.NET). - MSDN
Ensure your reference to the file is spelled and pathed correctly
Example: "/Resources/logo.png" if you have a folder at the project level
Notice the prefix /.
Colors codes in the xaml file missing the hashtag prefix "#000FE0"
In my case, another program was using the image and somehow was blocking the access.
I mad a copy and this worked.
<Window
.....
Height="450" Width="400"
Icon="../Resources/SettingsCopy.png" >
To improve upon user2125523:
If you've added the image to the project and checked and double checked that the file spelling is correct, try renaming the image to mirror a different existing image. Build/run, then put your image file name back and build/run again.
For example:
My original code kept throwing the OP error on LargeImage="/img/32/delete.order.png" even though this file exists.
<telerik:RadRibbonButton Text="Object Properties" Size="Large"
Name="PropertiesButton" IsTabStop="True"
telerik:ScreenTip.Description="Get object properties"
Click="PropertiesButton_Click"
LargeImage="/img/32/properties.png"
SmallImage="/img/16/properties.png" />
<telerik:RadRibbonButton Text="Reset Tab Order" Size="Large"
Name="ClearTabOrderButton" IsTabStop="True"
telerik:ScreenTip.Description="Reset tab order of all fields"
Click="ClearTabOrder_Click"
LargeImage="/img/32/delete.order.png"
SmallImage="/img/16/delete.order.png" />
So, I changed LargeImage="/img/32/delete.order.png" to LargeImage="/img/32/properties.png", ran the program, and changed it back to "/img/32/delete.order.png". Finally the error was gone.
FYI VS2012.3 Win8.1Preview
I had the same issue and to add an image to you solution you have to do it through the wizzard. In the solution explorer -> right click on the appropriate folder-> add existing Item -> and then browse to your image. That worked for me. Hope this helps.
Thanks for you answers.
Try to set Build Action of Property of Image file as Resource.
Exception used to occur within constructor. Button's command binding was incorrect.
Eg: <Button Command="MyCommand" />--> Wrong
<Button Command="{Binding MyCommand}" />--> Right
In my case, I got this error when I had
<Border Background="eeeeee">
instead of
<Border Background="#eeeeee">
(notice the missign #)
I found "UpdateSourceTrigger=Pr" somewhere in my XAML.
Must have happened during editing.
Compiling went OK, no error then whatsoever.
Setting a BreakPoint in Application_DispatcherUnhandledException in app.xaml.cs revealed the error.
Corrected to "UpdateSourceTrigger=PropertyChanged" and the world was at it should have been.
I work on Win 10 Pro, VS2017
I encountered this error and figured out that the Image Source path format has a mistake. a forward slash / was added as follows:
Source="/TestProject;component/Images//hat_and_book.png
I removed that extra slash and the error had gone.
I got the same error message, then I find this solution :
Image not displaying at runtime C# WPF
Find your folder:Go to properties of the added image, set Build Action =>as Resource and Copy To Output Directory =>as Copy if newer.
In My case I have wrote a border tag with height property then i had to remove the value leaving the property like this
<Border Background="{StaticResource MainBackgroundBrush}" BorderThickness="1" Height="">
</Border>
The Compiler gave me the same error but the IDE have no problem so after some hard search i have found it. so make sure every property is properly set. I hope this would be useful for anyone.
it is caused by Non-standard tag option in xaml to find it set
InitializeComponent();
Function in - try mode - like this
try {
InitializeComponent();
}
catch (Exception ex) {
MessageBox.Show(ex.Message.ToString());
}
now MessageBox(( show line number with incorrect setting in control .axml file.(it just show first incorrect line tag error after Corrected it then run app again and see next one)