简体   繁体   English

C#Wpf自定义转换器已创建但未调用

[英]C# Wpf Custom Converter is created but not called

I've got XAML parse exception "BitmapImage UriSource must be set". 我有XAML解析异常“必须设置BitmapImage UriSource”。 While parsing, my converter is created, but Convert() method is not called. 解析时,将创建我的转换器,但未调用Convert()方法。 What am I doing wrong? 我究竟做错了什么?

XAML: XAML:

<ImageBrush >
    <ImageBrush.ImageSource>
          <BitmapImage UriSource="{Binding Path=Value.Image, Converter={StaticResource imageConverter}, ConverterParameter=Value.Image}" CacheOption="OnLoad"></BitmapImage>
    </ImageBrush.ImageSource>
</ImageBrush>

C#: 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 : 由于只需要使用<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");
    }
}

And XAML: 和XAML:

<ImageBrush ImageSource="{Binding Path=Value.Image, Converter={StaticResource imageConverter}}">
</ImageBrush>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM