[英]Binding Image Source with Dependency Property
I'm working on a custom control. 我正在开发一个自定义控件。 This custom control has an image in it like this:
此自定义控件中的图像如下所示:
<Image Source="{TemplateBinding Poster}" />
In my C# file, the DependencyProperty
is the following: 在我的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); }
}
Now I can add the following to my user control in XAML: Poster="Images/NoPoster.png"
or Poster = new BitmapImage(new Uri(@"pack://application:,,,/Images/NoPoster.png"))
from code. 现在,我可以在XAML中将以下内容添加到我的用户控件中:
Poster="Images/NoPoster.png"
或Poster = new BitmapImage(new Uri(@"pack://application:,,,/Images/NoPoster.png"))
。
Everything is working fine. 一切正常。 What I'm wondering is, why can't I declare
Poster
as BitmapImage
or string
instead of ImageSource
? 我想知道的是,为什么我不能将
Poster
声明为BitmapImage
或string
而不是ImageSource
?
You can of course declare it as BitmapImage
. 您当然可以将其声明为
BitmapImage
。 But that would be an unnecessary restriction, because the base class ImageSource
is sufficient. 但这将是不必要的限制,因为基类
ImageSource
就足够了。
You can also use string
or Uri
as property type, but then you should replace the TemplateBinding by a regular Binding, because source and target property types no longer match, and built-in automatic type conversion should take place: 您还可以使用
string
或Uri
作为属性类型,但是随后您应该用常规的Binding替换TemplateBinding,因为源和目标属性类型不再匹配,并且应该进行内置的自动类型转换:
<Image Source="{Binding Poster, RelativeSource={RelativeSource TemplatedParent}}" />
Note that you do not need an explicit binding converter, because type conversion is performed automatically by the ImageSourceConverter
class, which is registered as type converter for ImageSource
. 请注意,您不需要显式绑定转换器,因为类型转换是由
ImageSourceConverter
类自动执行的,该类已注册为ImageSource
类型转换器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.