WPF: Binding to Properties in your UserControl or Window
One of the problems I came across when first doing Windows Presentation Foundation (WPF) control development is the need to bind to properites that I create in my UserControl that are to be set by the consumer of the control. The way you do this may not be the most straight forward, but it works nicely once you get a hold of it.
There are three steps to binding to custom properties:
-
Create a dependency property (if you don't know what this is yet, read up on it. They are an important component of XAML and WPF)
-
Name your user control in your XAML using the standard x:Name="myUcName".
-
Create a binding to the element in XAML, in this example, an Image control has its Source bound to a Source property on the user control: <Image Source="{Binding ElementName=myUcName, Path=Source}" />
In the end, a basic control that wraps the Image control and sets its source would look something like this:
User Control:
<UserControl x:Class="Decav.WpfSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="myUcName">
<Image Source="{Binding ElementName=myUcName, Path=Source}" x:Name="img"/>
</UserControl>
Code Behind:
/// <summary>
/// The dependency property that gets or sets the nsource of the image to render.
/// </summary>
public static DependencyProperty SourceProperty = DependencyProperty.Register(
"Source", typeof(ImageSource), typeof(WpfSample));
/// <summary>
/// Gets or sets the nsource of the image to render.
/// </summary>
public ImageSource Source
{
get { return (ImageSource)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
And with that, your Image.Source will point to the WpfSample.Source (your user control), and vice versa, getting updated when the Source property changes on either.
Good luck with your WPF adventures!