I am trying to load BitmapImage at runtime from a URI. I use the default image in my XAML user control, which I would like to replace with data binding. It works.
The problem I ran into is when an invalid file is used for the replacement image (maybe this is an invalid URI, or maybe the URI indicates a file without an image). When this happens, I want to check the BitmapImage object to make sure that it was loaded correctly. If not, I want to stick with the default image used.
Here's the XAML:
<UserControl x:Class="MyUserControl">
<Grid>
<Image
x:Name="myIcon"
Source="Images/default.png" />
</Grid>
</UserControl>
And the corresponding codebehind:
public static readonly DependencyProperty IconPathProperty =
DependencyProperty.Register(
"IconPath",
typeof(string),
typeof(MyUserControl),
new PropertyMetadata(null, new PropertyChangedCallback(OnIconPathChanged)));
public string IconPath
{
get { return (string)GetValue(IconPathProperty); }
set { SetValue(IconPathProperty, value); }
}
private static void OnIconPathChanged(
object sender,
DependencyPropertyChangedEventArgs e)
{
if (sender != null)
{
MyUserControl control = sender as MyUserControl;
if (control != null)
{
control.UpdateIcon();
}
}
}
public void UpdateIcon()
{
BitmapImage replacementImage = new BitmapImage();
replacementImage.BeginInit();
replacementImage.CacheOption = BitmapCacheOption.OnLoad;
replacementImage.UriSource = new Uri(IconPath, UriKind.RelativeOrAbsolute);
replacementImage.EndInit();
if (replacementImage.UriSource != null)
{
myIcon.Source = replacementImage;
}
}
And here is how I can create an instance of this user control in another XAML file:
<MyUserControl IconPath="C:\\example.png" />
, , - / . .