Monday, February 28, 2011

Using Code Behind For Property Binding in WPF

This is a very common thing in WPF, but after being away from WPF for some time, I often have to look it up. In order to bind to properties in the code behind, you need to set the DataContext of the window to "self" as per example below:

<Window x:Class="MyProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">

        <Label Content="{Binding StatusText}"/>
</Window>

Now you can bind to a dependency property like this in your code behind:

public string StatusText
{
    get { return (string)GetValue(StatusTextProperty); }
    set { SetValue(StatusTextProperty, value); }
}

public static readonly DependencyProperty StatusTextProperty =
    DependencyProperty.Register("StatusText", 
typeof(string), typeof(MainWindow), new UIPropertyMetadata(""));

0 comments:

Post a Comment