加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-13 20:30:20 所属栏目:Windows 来源:网络整理
导读:我正在代码中创建一个Image.Source-String绑定: var newBinding = new System.Windows.Data.Binding() { Path = new PropertyPath("MyImageUrl") };BindingOperations.SetBinding(attachedObject,Image.SourceProperty,newBinding); 这种方法适用于,例如,Te
我正在代码中创建一个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有一个问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读