Tuesday, March 11, 2008

ItemsControl, ListBox and DataGrid's, oh my

The ItemControl's coolest use is to layout 'items' via an item template using data binding to a collection. As a functional control this really requires more than just some Xaml and in fact we will walk through the process in order so we never have Visual Studio throwing some errors. In your page behind you will need to make sure you include these libraries as show here:

using System.ComponentModel;
using System.Collections.ObjectModel;

This gives us access to ObservableCollection and INotifyPropertyChanged so we can build out our data. We will create a method that create our collection but first we need a base classes for our data. To start with we need to create the Data class first like this:

public class Data : INotifyPropertyChanged
{
private object _value;
public event PropertyChangedEventHandler PropertyChanged;

public Data(object val) { _value = val; }

private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}

This inherits from INotifPropertyChanged and we create our NotifyPropertyChanged method along with a constructor so we can pass our value in when we create instances of the class. Since we have a private value we need to expose it publicly so we can then bind our templates to it as used in the items control. So then we add the following code to the above class:

public object Value
{
get { return _value; }
set
{
if (value != _value)
{
_value = value;
NotifyPropertyChanged("Value");
}
}
}

This 'Value' public property is what we will actually bind to. Then we can create our DataCollection that is an ObservableCollection of our Data Class like this:

public class DataCollection : ObservableCollection<Data> { }

Now we have an ObservableCollection that we can bind to. Next we need to create a method that creates or gets the data. Here we will hard code the data into this simple example:

private object GetData()
{
DataCollection MyCollection = new DataCollection();
MyCollection.Add(new Data("One"));
MyCollection.Add(new Data("Two"));
return MyCollection;
}

Let us now look at our Xaml, now that we have our collection and something to create it or fill it with data we need an items control and template to do something with. First we build our template for each item that will be listed in the items control.

<UserControl.Resources> <DataTemplate x:Name="MyDataTemplate" > <TextBlock Text="{Binding Value}" ></TextBlock> </DataTemplate> </UserControl.Resources>

This will bind to the public value of 'Value' as created in our data class earlier. Next we need to actually create the items control. An Items control can be as simple as this:

<ItemsControl x:Name="itemsControl" ItemsSource="{Binding}" ItemTemplate="{StaticResource MyDataTemplate}" >
</ItemsControl>

In this case we set our ItemSource to be Binding and then we use a static resource namely our template. Back to our code we now need to point the items control to the method that creates our collection using code like this:

this.itemsControl.DataContext = GetData();

This can be in our page's or user controls constructor and sets the data context to be the collection of objects as an observable collection that we are building and returning. When we run this we will get a list of items as created in the GetData method much like a stack panel would lay out its children where in this case the default is vertically.

Not terribly impressive but under the covers very cool. What is most cool about it is the key functionality this provides. This can be used for everything from dynamically build menus and other dynamic lists of different kinds and more. To move beyond that we can also use the new control Listbox.

Using the Listbox control

The Listbox control is much like the ItemsControl but we are adding functionality including scrolling and selection rollover functionality. We can style it and using databinding and the like just the same. So using the code from the last section we can change out our Xaml and be ready. To start with add additional elements in the collection in our source this way we have 20 or so elements so we can see the scroll functionality. Then we can remove the ItemsControl and add a Listbox like this example:

<ListBox x:Name="itemsControl" Grid.Row="1"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource MyDataTemplate}" />

So by adding all the extra items to our collection we can really see the big difference between ItemsControl and Listbox control.

With the Listbox control it is easier to implement functionality like select or drop down functionality that users see in other technologies. Now to take this even one step further lets look at DataGrid.

Using the Datagrid Control

The Datagrid is used much like the list and items controls but the datagrid is targeted towards result set functionality. In this case we need to make sure we specify the name space in the xaml. At the top if you use Visual Studio and start to create a name space it will give you a list and you want to select the 'System.Windows.Control.Data'. You can give your 'namespace' any name you want but since it's a Datagrid we are talking about I'm partial to 'Data' as a matter of course. So lets assume the same code base as the Listbox we did earlier, then rip out our 'ListBox' and then add this bit of Xaml

<Data:DataGrid x:Name="itemsControl" AutoGenerateColumns="True" ItemsSource="{Binding}" />

When we run this we get a nice data grid like the ListBox but we get column names. We can of course re-template this to look pretty much any way we like but default will look pretty much like any data grid control you might see in winforms.

As you can see its pretty much the same as the ListControl and ItemsControl but Columns are added and we have set it to auto-generate the columns.

1 comment:

  1. Thanks, this is the info I was looking for. Much appreciated.

    ReplyDelete