我创建了一个小型用户控件,其中包含一个内容为图像的按钮。我在用户控件上创建了一个“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) 实例...
该怎么办?