Reputation: 3009
I am creating a custom WPF control that uses an image inside of it. This custom control will be like any other, it will be declared in xaml. I want to have a public property for this control to specify the source of the internal image, much the same way you do this when using an Image control:
<Image Source="http://foo.com/bar.jpg"></Image>
What I want to do is have the following usage of my control:
<MyCustomControl ImageSource="http://foo.com/bar.jpg"></MyCustomControl>
And then internally, something like:
<UserControl class="MyCustomControl" ...>
<Image Source="{Binding Imagesource}"></Image>
</UserControl>
What kind of setup do I need in my codebehind to get this to work? i've tried a few things but can get nothing to work.
Upvotes: 0
Views: 163
Reputation: 185300
What you need is a dependency property of type ImageSource
and a proper binding, either use ElementName
or RelativeSource
, do not use the DataContext
on UserControls
.
<UserControl Name="control" x:Class="MyCustomControl" ...>
<Image Source="{Binding ImageSource, ElementName=control}"/>
</UserControl>
<UserControl x:Class="MyCustomControl" ...>
<Image Source="{Binding ImageSource,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>
Upvotes: 2