コンテンツがイメージであるボタンで構成される小さなユーザー コントロールを作成しました。ボタン内のイメージからユーザー コントロールにバインドするために、ユーザー コントロールに "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)インスタンスに変換しません...
何をすべきか?