I'm creating an Image.Source
-String
binding in code like:
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 the Image.Source
-String
I ideally would like the Binding
to automatically insert a conversion for me - in the same way that the Xaml binding does when I use:
<Image Source="{Binding ImageUrl}" />
I realise I can add my own converter to mimic the Xaml binding behaviour, but I'd like to see if there's some way to do exactly what the Xaml does.
Is there some way to get the new Binding
to automatically add it's own string->BitmapImage ValueConverter
during the code-based bind evaluation?
System.Windows.Media.ImageSource has a TypeConverterAttribute
[TypeConverter(typeof(ImageSourceConverter))]
The binding will look for this and use the converter automatically.
If you look at the ImageSourceConverter
you can see what types it can convert from:
if (sourceType == typeof(string) ||
sourceType == typeof(Stream) ||
sourceType == typeof(Uri) ||
sourceType == typeof(byte[]))
{
return true;
}
In order to mimic this process, you must add a TypeConverterAttribute
on the Type of the property being bound to.
You can do this by 1. controlling the type, or 2. use the TypeDescriptor
at runtime to add the attribute. There's a question about this here.
来源:https://stackoverflow.com/questions/16752242/how-does-xaml-create-the-string-to-bitmapimage-value-conversion-when-binding-to