绑定依赖关系的图像源 属性
Binding Image Source with Dependency Property
我正在开发自定义控件。这个自定义控件中有一个像这样的图像:
<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
声明为 BitmapImage
或 string
而不是 ImageSource
?
当然可以声明为BitmapImage
。但这将是一个不必要的限制,因为基数 class ImageSource
就足够了。
您也可以使用 string
或 Uri
作为 属性 类型,但是您应该将 TemplateBinding 替换为常规绑定,因为源和目标 属性 类型不再匹配,应该进行内置的自动类型转换:
<Image Source="{Binding Poster, RelativeSource={RelativeSource TemplatedParent}}" />
请注意,您不需要显式绑定转换器,因为类型转换由 ImageSourceConverter
class 自动执行,它已注册为 ImageSource
的类型转换器。
我正在开发自定义控件。这个自定义控件中有一个像这样的图像:
<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
声明为 BitmapImage
或 string
而不是 ImageSource
?
当然可以声明为BitmapImage
。但这将是一个不必要的限制,因为基数 class ImageSource
就足够了。
您也可以使用 string
或 Uri
作为 属性 类型,但是您应该将 TemplateBinding 替换为常规绑定,因为源和目标 属性 类型不再匹配,应该进行内置的自动类型转换:
<Image Source="{Binding Poster, RelativeSource={RelativeSource TemplatedParent}}" />
请注意,您不需要显式绑定转换器,因为类型转换由 ImageSourceConverter
class 自动执行,它已注册为 ImageSource
的类型转换器。