AdSense

Wednesday 28 August 2013

C# WPF - DataBinding

(Deutsche Version) DataBindings in WPF are very powerful and useful. Today, I will explain the basics. The basic idea is: I have a display element and a variable (technically: field). When I change my variable, I want the display element to change and vice versa, so the variable will change if the display element changes (e.g. a text is entered into a TextBox). At first the XAML part of the code:

<TextBox Name="InputText" Grid.Row="0" Text="{Binding BindingText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBox>
<TextBlock Name="OutputText" Grid.Row="1" Text="{Binding BindingText, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"></TextBlock>


As a next step, I need an object to which I am doing the DataBinding. In my case, this is the class "AnyClass" which containt the field "BindingText". I could also simply use MainWindow.xaml.cs. To define the object to which the bining should be, you have to do the following:

AnyClass anyClass = new AnyClass();
InputText.DataContext = anyClass;
OutputText.DataContext = anyClass;


I could also do this.DataContext = anyClass;, this would have the same effect but I want to show different possibilities how to do DataBinding. I also could also create the field "BindingText" in MainWindow.xaml.cs and then do this.DataContext = this;.

Now I want to face the class AnyClass. At first a short introduction to fields. A field can be used just like a variable but it cannot hold values directly. The minimum field would be this:

public string BindingText
{
    get { return _BindingText; }
    set { _BindingText = value; }
}
private string _BindingText = "";


This is a field. The get and set parts can do lots of funny things like checking the input, throw events, and everything else.

Now I will show the class AnyClass which is the last missing part for the DataBinding:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBindingExample
{
    public class AnyClass : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public string BindingText
        {
            get { return _BindingText; }
            set
            {
                _BindingText = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs("BindingText"));
                }
            }
        }
        private string _BindingText = "<empty>";
    }
}


By calling PropertyChanged, the display element gets the information that there is a new variable value and refreshes the displayed value. This should cover the basics for DataBinding. If there are further questions, I will answer them in the comments.

 A post about this topic who also covers converters can be found on C# Tips and Tricks.

No comments:

Post a Comment