Per Erik Strandberg /cv /kurser /blog

What is a data binding?

A Data Binding is the powerful WPF-way to auto-update data between the business model and the user interface. OK, and what does that mean? It means that by sending an event from for example a data base the user interface magically reloads entries into a table. It can also mean that by altering the entries in a table (in the user interface) the data base is magically updated. The data binding can also go both ways.

A first example and the Binding keyword

Let's look at a "simple" example from [1] where we only add a few short lines to the XAML-code and end up with our very first databinding.

    <TextBox Name="txtInput" />
    <Label Content="{Binding Text, ElementName=txtInput, 
                     UpdateSourceTrigger=PropertyChanged}" />

Before we look into what this means let's take a look at the surprising results in the below screen shot. We here have a text box at the top, and everything we type into it is magically reproduced into the label below it.

How is this possible!?! We haven't written any "code". What you would have expected is to implement an event handler that sniffs the events from the text box, and if there is a property changed event then you'd copy the text from the text box into to label. Hmmm... Perhaps this data binding stuff can save me a lot of trouble - the old way just sounded a little complicated and this new way looks easy. I just have to understand it a bit better.

OK, let's take a look at the code to see what is in there. We have a text box with no magic in it what so ever: <TextBox Name="txtInput" />. So the magic must be happening in the XAML of the Label - let's split it up on a few lines so we can read it better:

<Label Content="
    Binding Text, 

Inside the curly bracket we find the Binding keyword and then text - so we want to bind text into the label. Next we have the element name txtInput - so the text we want to bind is coming from the text box. Last we have a reference to the property changed event of the text box - this is when we want to trigger a synchronization of the text.

Complicating things with a ValueConverter

I guess you might have noticed that I always refer to Wikipedia - well my colleagues are starting to bug me for that. I am also a bit annoyed by the very long text in the label in the above example. Let's change that with a ValueConverter - these are normally used when you have to data bind properties with incompatible types.

We want something like this:

There are a few changes we need to do in order to achieve this: first we need to implement a converter, and second add some more magic in the XAML code.

The value converter

Now you need to add some C# code - specifically a class that implements the interface IValueConverter:

    public class MyTextConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            // Remove wikipedia
            string input = (string)value;
            input = input.Replace("Wikipedia", "Obscure Sources");

            // Cut last chars
            int n = 64;
            if (input.Length > n)
                input = input.Substring(0, n) + "...";

            return input;

        // not used in this example
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            throw new NotImplementedException();

Updates in the XAML

Take a look at the xml name spaces at the top of the XAML file - they need to look something like the below. Here we have added a reference to the C# code name space and also two prefixes x and l that are used later.


Inside the windows element before the stack panel we declare a resource - our converter:

        <l:MyTextConverter x:Key="my_converter" />

We finally declare that the converter should be used inside the data binding within the content of the label:

    <Label Content="{
        Binding Text, 
        Converter={StaticResource my_converter}

This page belongs in Kategori Programmering