Xaml 如何在绑定到 Image.Source 时创建字符串到 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.
在基于代码的绑定评估期间,有什么方法可以让新的 Binding
自动添加它自己的字符串->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.
这篇关于Xaml 如何在绑定到 Image.Source 时创建字符串到 BitmapImage 值的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!