c# - IValueConverter 获取空值 - WPF C#

标签 c# wpf image converters ivalueconverter

我正在尝试使用 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/

相关文章:

c# - 如何管理 MTP 可移植设备上的文件?

c# - 鼠标滚动选中和取消选中 DataGrid 中的复选框

wpf - 如何将 XAML Storyboard动画添加到 XBAP 中的完整 WPF 自定义控件?

c# - 如何使用 xamarin 将私有(private)字符放入字符串中

c# - 我应该将 LINQ DataContext 保留多长时间? ASP.Net页面

c# - 让窗口根据一个控件的大小而不是另一个控件的大小增长

python - 一半图像在 elif 语句中模糊

android - 读取图像文件

c++ - 在 OpenCV 中逐像素复制图像

c# - 带有数字和特殊字符但没有字母的正则表达式