Monday, June 2, 2014

Pitfalls of using WPF DataGrid

WPF DataGrid is a very powerful Control that was first published within the WPF Toolkit. Since .NET 4.0 the WPF DataGrid is part of the .NET Framework. The simplest way to use it, is to set the ItemsSource, only.
<DataGrid ItemsSource="{Binding Source1}" />
public ICollection<IValue> Source1 { getset; }
Due to the AutoGenerateColumns property, which default value is true, the DataGrid is created with the properties of the class that is used within the collection. In order that this works
  • the binded collection must be public
  • the properties of the used class must be public
For example the interface could look like that
public interface IValue
{
    string Val { get; }
    string Key { get; }
}
and the implementation of the interface could look like that
public class KeyVal : IValue
{
    public KeyVal(string key, string val)
    {
        Key = key;
        Val = val;
    }
 
    public string Val
    {
        get;
        private set;
    }
 
    public string Key
    {
        get;
        private set;
    }
}
All that results into

As you can see columns are auto-generated and filled with the objects of the binded list.
For just viewing collections this is all you have to consider. If you want also add new entries to the collection there must be done some changes. In the XAML part the CanUserAddRows property indicates if it is possible to add new entries. The default value is true, so the XAML part remains unchanged. In code we have to do some changes
  • the generic type of the collection must be a class (not an interface)
  • there must be a default constructor (parameterless) in the generic type of the collection
public ICollection<KeyVal> Source1 { getset; }
public class KeyVal : IValue
{
    public KeyVal()
    {
 
    }
 
    public KeyVal(string key, string val)
    {
        Key = key;
        Val = val;
    }
 
    public string Val
    {
        get;
        set;
    }
 
    public string Key
    {
        get;
        set;
    }
}
Only with these changes a new object can be created from the view and added to the collection. As result there is a new empty entry in the DataGrid that can be filled by the user and is then added to the collection.