当绑定到Image.Source时,Xaml如何创建BitmapImage值转换的字符串? [英] How does Xaml create the string to BitmapImage value conversion when binding to Image.Source?
问题描述
我正在创建一个 Image.Source
- String
在代码中绑定如下:
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);
此方法适用于例如 TextBlock.TextProperty
- String
绑定,但对于 Image.Source
- String
我理想地希望
Binding
自动为我插入一个转换 - 与我使用的Xaml绑定时一样:
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}" />
我意识到我可以添加自己的转换器来模拟Xaml绑定行为,但我想看看是否有一些方法可以做到Xaml所做的一切。
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.
有没有办法获得新的绑定
在基于代码的绑定评估期间自动添加自己的字符串 - > BitmapImage ValueConverter
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有一个 TypeConverterAttribute
System.Windows.Media.ImageSource has a TypeConverterAttribute
[TypeConverter(typeof(ImageSourceConverter))]
绑定将寻找这个并使用转换器自动。
The binding will look for this and use the converter automatically.
如果您查看 ImageSourceConverter
,您可以看到可以转换的类型:
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;
}
为了模仿此过程,您必须添加一个 TypeConverterAttribute
对于绑定的属性的类型。
In order to mimic this process, you must add a TypeConverterAttribute
on the Type of the property being bound to.
您可以通过以下方式执行此操作:1.控制类型,或2.使用 TypeDescriptor
在运行时添加属性。有关于此此处的问题。
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.
这篇关于当绑定到Image.Source时,Xaml如何创建BitmapImage值转换的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!