我正在尝试使用 CroppedBitmap。
图像的路径只有在运行时才知道,所以我想通过 Binding 设置 CroppedBitomap.Source。
我发现 CroppedBitmap 及其源存在一个已知问题。请参阅:WPF - using CroppedBitmap in DataTemplate
这些链接建议使用转换器。 我尝试这样做,但我总是在 Convert 函数中得到空值。
这是一个 xaml View :
<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 时,我发现名为“value”的第一个参数始终为 null。
大师们,我需要你的帮助。
最佳答案
我也遇到了同样的问题。
我的错误是绑定(bind)的属性类型错误。它是字符串,应该是一个枚举。
没有构建错误。 但在运行时我的 (IValueConverter).Convert 方法传递 value=null。
发生这种情况的地方 - 检查绑定(bind)...
关于c# - IValueConverter 获取空值 - WPF C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567272/