Krowi Krowi - 3 months ago 25
C# Question

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:

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.

Everything is working fine. What I'm wondering is, why can't I declare
Poster
as
BitmapImage
or
string
instead of
ImageSource
?

Answer

You can of course declare it as BitmapImage. But that would be an unnecessary restriction, because the base class ImageSource is sufficient.

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:

<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.

Comments