【问题标题】:How does Xaml create the string to BitmapImage value conversion when binding to Image.Source?Xaml绑定Image.Source时如何创建字符串到BitmapImage值的转换?
【发布时间】:2013-05-25 17:40:52
【问题描述】:

我正在使用如下代码创建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 在基于代码的绑定评估期间自动添加它自己的字符串->BitmapImage ValueConverter?

【问题讨论】:

  • 我不确定我是否理解正确。您要绑定的属性 (MyImageUrl) 的类型是什么?因为您提供的代码相当于在 Xaml 中执行 。该属性可以是字符串、Uri 或 ImageSource,并且应该适用于所有情况。
  • 否 - 如果我在代码中创建该精确绑定,则它无法用于字符串。
  • 嗯。我刚试过,工作正常。您是否有任何异常或图像不显示?
  • 有趣 - 在 wp7 模拟器或 wp8 手机上不适合我。你尝试了什么? wp7? wp8?其他?
  • 我在 wp8 上试过。这可能听起来很傻,但你能仔细检查你的属性是否返回了正确的图像路径字符串?

标签: xaml data-binding windows-phone-8 windows-phone dependency-properties


【解决方案1】:

System.Windows.Media.ImageSource 有一个TypeConverterAttribute

[TypeConverter(typeof(ImageSourceConverter))]

绑定会自动查找并使用转换器。

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

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

为了模拟这个过程,您必须在要绑定的属性的类型上添加TypeConverterAttribute。

您可以通过 1. 控制类型或 2. 在运行时使用 TypeDescriptor 添加属性来做到这一点。有一个关于这个here的问题。

【讨论】:

  • 谢谢。我认为我遇到的问题是 Wp7 上的行为有所不同......在 Wp8 上,这似乎工作得很好。
猜你喜欢
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多