Data binding to static properties

With WPF 4.5 we can now bind to static properties. Let's see how.

Getting ready

In order to use this recipe you should have Visual Studio 2012 installed.

How to do it...

In this recipe, we are going to see how to use the capability of WPF in .NET 4.5 to bind to static properties as well as how to define and notify their property changes.

  1. First, open Visual Studio 2012 and create a new project. We will select the WPF Application template from the Visual C# category and name it WPFStaticPropertiesBinding.
  2. Add a class and name it MyStaticDetails.cs, adding the following code:
    public class MyStaticDetails
    {
        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
        protected static void OnPropertyChanged(string propertyName)
        {
            if (StaticPropertyChanged != null)
                StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
        }
    
    
        private static int myAge;
        public static int MyAge
        {
            get { return myAge; }
            set {
                myAge = value;
                OnPropertyChanged("MyAge");
            }
        }
    
        private static string myName;
        public static string MyName
        {
            get { return myName; }
            set {
                myName = value;
                OnPropertyChanged("MyName");
            }
        }
    }
  3. Open the MainWindow.xaml.cs code and change the MainWindow class code as follows:
    public MainWindow()
    {
        InitializeComponent();
    
        MyStaticDetails msd = new MyStaticDetails();
        MyStaticDetails.MyAge = 40;
        MyStaticDetails.MyName = "Jose Louis";
    
        this.DataContext = msd;
    }
  4. Open the MainWindow.xaml view and add two rows and two columns to the grid, then add two labels and two TextBox controls, and finally a binding expression to their Text property. The resulting XAML code should be similar to the following:
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="21:"/>
            <ColumnDefinition Width="64:"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="29.6"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Label Content="Name: " />
        <Label Content="Age: " Grid.Row="1"/>
        <TextBox Grid.Column="1" TextWrapping="Wrap" 
                   Text="{Binding MyName, Mode=TwoWay}" 
                   Margin="2"/>
        <TextBox Grid.Column="1" Grid.Row="1" TextWrapping="Wrap" 
                   Text="{Binding MyAge, Mode=TwoWay}" 
                   Margin="2"/>
    </Grid>
  5. Add a breakpoint on the MyName setter.
  6. Execute the application; we should see the following screen:
    How to do it...
  7. Go to the Name field and change it to Pancho, for example.
  8. When we move the cursor out of the textbox (for example, by pressing the Tab key), we will see that the break point is properly hit so the binding works on both directions, as expected.

How it works...

We implemented one of the two static events that we have in .NET 4.5 to notify changes in static properties, specifically the StaticPropertyChanged event. We used it to pass a PropertyChangedEventArgs event to provide, in turn, the name of the property being changed. The implementation is very similar to that of our non-static PropertyChanged event.

public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
protected static void OnPropertyChanged(string propertyName)
{
    if (StaticPropertyChanged != null)
        StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}

As we already did with the NotifyPropertyChanged event, we now call the method we defined, to raise our StaticPropertyChanged event:

OnPropertyChanged("MyAge");

The rest of the implementation is the creation of an instance of MyStaticDetails, adding a default value and setting this as DataContext of the MainWindow UI.

On the MainWindow UI, we set up a grid with two rows and columns where we have placed the headings as labels and the controls to display and edit the data as textboxes.

Finally, we added a binding expression for the Text property for the textbox, using TwoWay binding in a standard fashion.

There's more...

We could have implemented the other interface:

public static event EventHandler MyPropertyChanged;

However, we would have needed to implement it for every property, since the events are named for each individual property name. In our case, we would have had the events, MyAgeChanged and MyNameChanged. This can be implemented for a reduced set of properties but is definitely not scalable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset