简体   繁体   中英

WPF XAML Image.Source Binding supported Types

I have xaml like this:

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

Where is the best documentation to which types the Source property by default (without separate converter) can bind to?

bonus:

Are there differences in .NET versions?

I wan't to bind in XAML to a viewmodel. So please no codebind like "Image.Source = ...;".

What i discovered so far:

common sense answer:

  • any class derived from ImageSource

MSDN documentation is mostly useless:

MSDN Image Control

Source Property: Gets or sets the ImageSource for the image.

MSDN Image.Source Property

XAML Values
imageUri
System.String
A URI of the image file

The most usefull answer i found is in the .net source ImageSourceConverter.cs :

  • string (Uri-like path)
  • byte[]
  • Stream
  • Uri

The idea of the ImageSourceConverter is correct. A possible way is to implement your own Converter to support different types as source. To do this, we have to write a Converter which is converting different types into an object of type 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}}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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