IValueConverter获取null值 - WPF C#

时间:2012-05-12 20:41:46

标签: c# wpf image converter ivalueconverter

我正在尝试使用CroppedBitmap。

图像的路径只在运行时才知道,所以我想通过Binding设置CroppedBitomap.Source。

我发现CroppedBitmap及其Source存在已知问题。见:WPF - using CroppedBitmap in DataTemplate

这些链接建议使用转换器。 我试过这样做,但我总是在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时,我看到名为“value”的第一个参数总是为空。

大师,我需要你的帮助。

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。

我的错误是绑定的属性是错误的类型。这是字符串应该是一个枚举。

没有构建错误。 但在运行时我的(IValueConverter).Convert方法传递的值= null。

发生这种情况 - 检查绑定......

相关问题