0

我创建了一个小型用户控件,其中包含一个内容为图像的按钮。我在用户控件上创建了一个“ImageSource”依赖属性,以便从按钮内的图像绑定到它。

但是,在我放置用户控件设置实例的 XAML 中,该属性会在运行时引发错误:

<ctrl:ImageButton ImageSource="/Resources/Images/Icons/x.png" Command="{Binding Reset}"  DisabledOpacity="0.1"/>

在运行时:

“/Resources/Images/Icons/x.png”字符串不是“ImageSource”类型的“ImageSource”属性的有效值。'ImageSource' 类型没有公共的 TypeConverter 类。

然后我创建了一个转换器:

public class StringToBitmapImage : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new BitmapImage(new Uri((string) value, UriKind.RelativeOrAbsolute));
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后用它装饰我的依赖属性:

    [TypeConverter(typeof(StringToBitmapImage))]
    public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register(
        LambdaHelper.GetMemberName<ImageButton>(ib => ib.ImageSource), typeof (ImageSource), typeof (ImageButton));
    [TypeConverter(typeof(StringToBitmapImage))]
    public ImageButton ImageSource
    {
        get { return (ImageButton)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }

但 WPF 仍然不会将我的字符串转换为 ImageSource (BitmapImage) 实例...

该怎么办?

4

1 回答 1

1

这里有几个不正确的地方:

首先,您的 CLR 属性返回一个ImageButton,而依赖项属性被定义为一个ImageSource.

其次,类型转换器与绑定值转换器不同。您的类型转换器应该从类派生TypeConverter并应用于ImageSource类而不是属性本身。

第三,框架ImageSource类型已经有一个TypeConverterAttributewithImageSourceConverter作为类型转换器,所以一切都应该开箱即用,而无需编写自定义转换器。确保您没有引用ImageSource另一个命名空间中的另一个自定义类。

最后,使用ImageBrush.ImageSource.AddOwner而不是重新定义一个全新的依赖属性。

编辑:回答Berryl的评论:

public static readonly DependencyProperty ImageSourceProperty = ImageBrush.ImageSource.AddOwner(typeof(ImageButton);

这段代码将重用现有的 ImageSource 属性,而不是定义一个新的(请记住,每个不同的依赖属性都在全局静态字典中注册),只定义一个新的所有者和可选的新元数据。这就像OverrideMetadata但来自外部班级。

于 2010-06-23T17:38:44.327 回答