WPF依赖项属性绑定

时间:2016-06-14 17:28:56

标签: wpf data-binding

我正在查看WPF控件(NotifyIconWpf https://bitbucket.org/hardcodet/notifyicon-wpf/src),我不太了解依赖属性的绑定是如何工作的。

该控件有一个名为TaskbarIcon.IconSource的依赖项属性,用于设置系统托盘图标的图标,我可以看到IconSource类型为ImageSource的代码。

但是在XAML中,它可以设置为IconSource="/Red.ico"之类的字符串,或者我可以将其绑定到IconSource="{Binding MyIcon}",其中MyIcon是DataContext中的字符串。

这个字符串如何神奇地转换为ImageSource ..我错过了这里明显的东西吗?

感谢阅读。

2 个答案:

答案 0 :(得分:2)

转换由ImageSourceConverter类完成,该类可以从stringUribyte[]转换为ImageSource

它被注册为ImageSource类的TypeConverter,如下所示:

[TypeConverterAttribute(typeof(ImageSourceConverter))]
public abstract class ImageSource : Animatable, IFormattable

在此处详细了解类型转换:TypeConverters and XAML

答案 1 :(得分:1)

此SO帖子回答了类似的问题:How does Xaml create the string to BitmapImage value conversion when binding to Image.Source?解释了这个过程。基本上,System.Windows.Media.ImageSource有一个TypeConverterAttribute,可以自动执行转换。