I've got XAML parse exception "BitmapImage UriSource must be set". While parsing, my converter is created, but Convert() method is not called. What am I doing wrong?
XAML:
<ImageBrush >
<ImageBrush.ImageSource>
<BitmapImage UriSource="{Binding Path=Value.Image, Converter={StaticResource imageConverter}, ConverterParameter=Value.Image}" CacheOption="OnLoad"></BitmapImage>
</ImageBrush.ImageSource>
</ImageBrush>
C#:
public class ImageConverter : IValueConverter
{
public ImageConverter()
{
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
try
{
return new BitmapImage(new Uri((string)value));
}
catch
{
return new BitmapImage();
}
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I've found kind of solution. Since I needed to use <BitmapImage>
only for setting CacheOption.OnLoad
so my local source file would not be locked, I've created custom ImageConverter
:
[ValueConversion(typeof(Uri), typeof(BitmapImage))]
public class ImageConverter : IValueConverter
{
public ImageConverter()
{
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
try
{
if(value == null)
{
return null;
}
var image = new BitmapImage();
image.BeginInit();
image.UriSource = value is Uri ? (Uri)value : new Uri(value.ToString());
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
return image;
}
catch
{
return null;
}
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException("Convert back function is not supported");
}
}
And XAML:
<ImageBrush ImageSource="{Binding Path=Value.Image, Converter={StaticResource imageConverter}}">
</ImageBrush>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.