简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM