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"
        Title="MainWindow" Height="350" Width="525" 
        Name="MyWindow"> <!-- 2. Name the Window -->
        <!-- 3. Bind using ElementName and Path -->
        <Label Content="{Binding ElementName=MyWindow,Path=MyRandomText}"/>

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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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