How does Xaml create a string to convert a BitmapImage value when binding to Image.Source?

I create an Image.Source - String binding in code, for example:

 var newBinding = new System.Windows.Data.Binding() { Path = new PropertyPath("MyImageUrl") }; BindingOperations.SetBinding(attachedObject, Image.SourceProperty, newBinding); 

This approach works well for, for example, TextBlock.TextProperty - String bindings, but for Image.Source - String I would ideally want Binding automatically insert the conversion for me - in the same way that Xaml binds when I use:

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

I understand that I can add my own converter to simulate the Xaml binding behavior, but I would like to see if there is a way to do exactly what Xaml does.

Is there a way to get a new Binding to automatically add its own string-> BitmapImage ValueConverter during code-based binding evaluation?

+1
source share
1 answer

System.Windows.Media.ImageSource has TypeConverterAttribute

 [TypeConverter(typeof(ImageSourceConverter))] 

The binding will look for it and automatically use the converter.

If you look at ImageSourceConverter , you will see what types it can convert from:

 if (sourceType == typeof(string) || sourceType == typeof(Stream) || sourceType == typeof(Uri) || sourceType == typeof(byte[])) { return true; } 

To emulate this process, you must add a TypeConverterAttribute to the type of the associated property.

You can do this using 1. type control or 2. use TypeDescriptor at runtime to add an attribute. There is a question about it here .

+4
source

Source: https://habr.com/ru/post/947771/


All Articles