CroppedBitmap を使用しようとしています。
画像のパスは実行時にしか分からないため、Binding を介して CroppedBitomap.Source を設定したいと考えています。
CroppedBitmap とそのソースに既知の問題があることがわかりました。参照: WPF - DataTemplate で CroppedBitmap を使用する
これらのリンクは、コンバーターの使用を推奨しています。やってみましたが、Convert 関数内で常に null 値を取得します。
以下は xaml ビューです。
<UserControl>
<UserControl.Resources>
<local:ImageConverter x:Key="imageConverter" />
</UserControl.Resources>
<StackPanel>
<Label x:Name="testLabel" Content="{Binding Path=Img}"/>
<Button x:Name="testButton" Content="{Binding ElementName=testLabel, Path=Content}"/>
<Image Stretch="None">
<Image.Source>
<CroppedBitmap Source="{Binding ElementName=testLabel, Path=Content, Converter={StaticResource imageConverter}}" SourceRect="10,10,50,50" />
</Image.Source>
</Image>
</StackPanel>
</UserControl>
「testLabel」という名前のラベルは、プロパティ Img からの値を問題なく表示します。ボタン「testButton」は、「testLabel」と同じ値を示します。
クラス imageConverter は次のとおりです。
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FormatConvertedBitmap fcb = new FormatConvertedBitmap();
fcb.BeginInit();
fcb.Source = new BitmapImage(new Uri((string)value));
fcb.EndInit();
return fcb;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("Cannot convert back");
}
}
しかし、関数 Convert をデバッグすると、「値」という名前の最初の引数が常に null になることがわかります。
達人、あなたの助けが必要です。