【问题标题】:WPF XAML Image.Source Binding supported TypesWPF XAML Image.Source 绑定支持的类​​型
【发布时间】:2016-10-23 20:19:10
【问题描述】:

我有这样的 xaml:

<Image Source="{Binding MyImage}" />

Source 属性默认(没有单独的转换器)可以绑定到哪些类型的最佳文档在哪里?

奖金:

.NET 版本有区别吗?

我不想在 XAML 中绑定到视图模型。所以请不要像“Image.Source = ...;”这样的代码绑定。

到目前为止我发现了什么:

常识回答:

  • 从 ImageSource 派生的任何类

MSDN 文档大多没用:

MSDN Image Control

Source 属性:获取或设置图像的 ImageSource。

MSDN Image.Source Property

XAML 值
imageUri
System.String
图片文件的 URI

我找到的最有用的答案是在.net 源代码ImageSourceConverter.cs

  • 字符串(类似 Uri 的路径)
  • 字节[]
  • 乌里

【问题讨论】:

  • 您已经列出了属性可以在没有绑定转换器的情况下绑定到的所有类型:ImageSourcestringUriStreambyte[],通过内置在类型转换中(通过 ImageSourceConverter 类)。对于任何其他源类型,您需要一个绑定转换器。
  • 这方面的文档在哪里?甚至这里也没有任何用户:msdn.microsoft.com/en-us/library/…
  • 虽然 WPF 的文档非常完善 (IMO),但仍然存在差距。但也有您已经找到的 Reference Source。参考那个。

标签: c# .net wpf xaml


【解决方案1】:

ImageSourceConverter 的思路是正确的。一种可能的方法是实现您自己的 Converter 以支持不同类型的源。为此,我们必须编写一个转换器,它将不同的类型转换为 ImageSource 类型的对象。这是第一种方法:

[ValueConversion(typeof(object), typeof(ImageSource))]
public class CustomImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ImageSource returnSource = null;

        if (value != null)
        {
            if (value is byte[])
            {
                //Your implementation of byte[] to ImageSource
                returnSource = ...;
            }
            else if (value is Stream)
            {
                //Your implementation of Stream to ImageSource
                returnSource = ...;
            } 
            ...          
        }
        return returnSource;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

通过使用此转换器的实例,您可以将不同的源类型作为对象传递给您的图像:

<Image Source="{Binding MyImage, Converter={StaticResource MyCustomImageConverter}}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2011-07-15
    • 2019-03-09
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多