使用依赖属性绑定图像源

时间:2016-08-23 16:46:58

标签: c# wpf xaml binding dependency-properties

我正在开发自定义控件。这个自定义控件有一个像这样的图像:

 <Image Source="{TemplateBinding Poster}" />

在我的C#文件中,DependencyProperty如下:

public static readonly DependencyProperty PosterProperty = DependencyProperty.Register(
    nameof(Poster), 
    typeof(ImageSource), 
    typeof(MovieButton), 
    new UIPropertyMetadata(null));

public ImageSource Poster
{
    get { return (ImageSource)GetValue(PosterProperty); }
    set { SetValue(PosterProperty, value); }
}

现在,我可以在XAML中将以下内容添加到我的用户控件中:Poster="Images/NoPoster.png"Poster = new BitmapImage(new Uri(@"pack://application:,,,/Images/NoPoster.png"))来自代码。

一切都很好。我想知道的是,为什么我不能将Poster声明为BitmapImagestring而不是ImageSource

1 个答案:

答案 0 :(得分:3)

您当然可以将其声明为BitmapImage。但这将是一个不必要的限制,因为基类ImageSource就足够了。

您也可以使用stringUri作为属性类型,但是您应该通过常规Binding替换TemplateBinding,因为源和目标属性类型不再匹配,并且内置自动类型转换应该发生:

<Image Source="{Binding Poster, RelativeSource={RelativeSource TemplatedParent}}" />

请注意,您不需要显式绑定转换器,因为类型转换是由ImageSourceConverter类自动执行的,该类已注册为ImageSource的类型转换器。