[英]C# Wpf Custom Converter is created but not called
我有XAML解析异常“必须设置BitmapImage UriSource”。 解析时,将创建我的转换器,但未调用Convert()方法。 我究竟做错了什么?
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();
}
}
我找到了一种解决方案。 由于只需要使用<BitmapImage>
来设置CacheOption.OnLoad
这样我的本地源文件就不会被锁定,因此我创建了自定义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");
}
}
和XAML:
<ImageBrush ImageSource="{Binding Path=Value.Image, Converter={StaticResource imageConverter}}">
</ImageBrush>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.