在绑定到Image.Source时,Xaml如何创建字符串到BitmapImage值转换?

我正在代码中创建一个Image.source-String绑定:
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绑定所做的那样:

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

我意识到我可以添加自己的转换器来模仿Xaml绑定行为,但是我想看看是否有某种方法可以完全实现Xaml的功能.

有没有办法让新的Binding在基于代码的绑定评估期间自动添加它自己的string-> BitmapImage ValueConverter?

System.Windows.Media.ImageSource有一个TypeConverterattribute
[TypeConverter(typeof(ImageSourceConverter))]

绑定将查找此并自动使用转换器.

如果您查看ImageSourceConverter,您可以看到它可以转换的类型:

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

为了模仿此过程,必须在要绑定的属性的Type上添加TypeConverterattribute.

您可以通过1.控制类型来执行此操作,或2.在运行时使用TypeDescriptor添加属性.关于这个here一个问题.

相关文章

Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...
Windows文件操作基础代码 Windows下对文件进行操作使用的一段...
Winpcap基础代码 使用Winpcap进行网络数据的截获和发送都需要...
使用vbs脚本进行批量编码转换 最近需要使用SourceInsight查看...