Bind WPF control to Window property

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:

  1. Create a dependency property, you can use the propdp code snippet
  2. Name the window, by setting the Name property in the <Window > tag
  3. 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>
Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.