我有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();
}
}
答案 0 :(得分:0)
我找到了一种解决方案。由于我只需要使用<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>