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>

About erictummers

My work as a recruited developer changes almost every month. 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s