I’ve decided to write this small post on how to bind a WPF control to a property of the Window code behind. Every time I forget one of the steps and end up searching for this:
- Create a dependency property, you can use the propdp code snippet
- Name the window, by setting the Name property in the <Window > tag
- Bind using ElementName and Path, set the Path to the dependency property (1) and ElementName to the window name (2)
Example with a label bind to a string property of the MainWindow.
// 1. create a dependency property with the propdp code snippet
public string MyRandomText
{
get { return (string)GetValue(MyRandomTextProperty); }
set { SetValue(MyRandomTextProperty, value); }
}
public static readonly DependencyProperty MyRandomTextProperty =
DependencyProperty.Register("MyRandomText", typeof(string),
typeof(MainWindow), new PropertyMetadata(Guid.NewGuid().ToString())
);
<Window x:Class="BindControlToWindowProperty.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Name="MyWindow"> <!-- 2. Name the Window -->
<Grid>
<!-- 3. Bind using ElementName and Path -->
<Label Content="{Binding ElementName=MyWindow,Path=MyRandomText}"/>
</Grid>
</Window>