【问题标题】:Binding Image Source with Dependency Property使用依赖属性绑定图像源
【发布时间】:2016-12-30 14:36:13
【问题描述】:

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

 <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

【问题讨论】:

    标签: c# wpf xaml binding dependency-properties


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 感谢您的回答。您的示例确实有效,而我首先追求的是。我认为设置字符串比先将其转换为Uri,然后再转换为BitmapImage 的工作量要少。你有什么建议,但更常用的方法是什么?
    • string 当然就足够了。但是,您可能希望利用 Uri 类执行的有效性检查。当您的控件的用户尝试传递无效的 URI 时,他们会收到异常。拥有并不是一件坏事。
    • 我知道这开始有点离题了,但是,Uri 有效性检查是什么意思?
    • 如前所述,您的控件的用户在尝试传递无效的图像 URI 时会收到异常。字符串不会发生这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多