在绑定到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有一个问题.

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...