Wednesday, March 09, 2011

WPF – Using Data Triggers

Data triggers are a great feature of WPF. They allow you to change the style properties of a control depending on the data of the bound items of that control.

In this tutorial, I am going to bind a set of data to a ListBox, and use Data Triggers to let me know when something is wrong.

So first, I am going to create a Person class. This class will have three public properties: Name, Age, and IsValid. All three properties will be readonly. The IsValid property will return whether the data of the class is good or not.

public class Person
{
    private string name;
    public string Name
    {
        get { return name; }
        private set { name = value; }
    }
    private int age;
    public int Age
    {
        get { return age; }
        private set { age = value; }
    }
    public bool IsValid
    {
        // will return false if either the name is blank
        //   or if the age is 0.
        get { return (!string.IsNullOrEmpty(name) && age != 0); }
    }