简体   繁体   English

WPF XAML Image.Source 绑定支持的类​​型

[英]WPF XAML Image.Source Binding supported Types

I have xaml like this:我有这样的 xaml:

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

Where is the best documentation to which types the Source property by default (without separate converter) can bind to?默认情况下 Source 属性(没有单独的转换器)可以绑定到哪些类型的最佳文档在哪里?

bonus:奖金:

Are there differences in .NET versions? .NET 版本是否存在差异?

I wan't to bind in XAML to a viewmodel.我不想在 XAML 中绑定到视图模型。 So please no codebind like "Image.Source = ...;".所以请不要像“Image.Source = ...;”这样的代码绑定。

What i discovered so far:到目前为止我发现了什么:

common sense answer:常识回答:

  • any class derived from ImageSource从 ImageSource 派生的任何类

MSDN documentation is mostly useless: MSDN 文档大多没用:

MSDN Image Control MSDN 图像控制

Source Property: Gets or sets the ImageSource for the image. Source 属性:获取或设置图像的 ImageSource。

MSDN Image.Source Property MSDN Image.Source 属性

XAML Values XAML 值
imageUri图像Uri
System.String系统字符串
A URI of the image file图像文件的 URI

The most usefull answer i found is in the .net source ImageSourceConverter.cs :我发现的最有用的答案是在 .net 源ImageSourceConverter.cs 中

  • string (Uri-like path)字符串(类似 Uri 的路径)
  • byte[]字节[]
  • Stream溪流
  • Uri乌里

The idea of the ImageSourceConverter is correct. ImageSourceConverter 的想法是正确的。 A possible way is to implement your own Converter to support different types as source.一种可能的方法是实现您自己的 Converter 以支持不同类型的源。 To do this, we have to write a Converter which is converting different types into an object of type ImageSource.为此,我们必须编写一个转换器,它将不同类型转换为 ImageSource 类型的对象。 Here is a first approach:这是第一种方法:

[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();
    }
}

By using an instance of this Converter, you are able to pass different source types as object to your Image:通过使用此转换器的实例,您可以将不同的源类型作为对象传递给您的图像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM