Posts Tagged ‘ItemsControl’

Important concepts of the ItemsControl

October 11, 2009 Leave a comment

The ItemsControl is the most versatile control in the WPF toolbox. This control, or one of its descendents like the ListBox, is so flexible in combination with custom controltemplates, datatemplates and panels that it can be used in countless situations. Well, countless… Dr. WPF has a great article with a test that you really should try!

Since the good doctor is the real specialist here when it comes to the ItemsControl, I just want to explain the basic concepts, because I noticed that a good number of questions on the WPF Forum wouldn’t have been asked if people new this.

There are enough examples on the internet that deal with directly adding items in xaml, so in the rest of this article I’m only going to talk about situations where the ItemsControl will get its items through DataBinding.

One of the key things to know about the ItemsControl is that every data item in your collection will get wrapped in another control. In case of an ItemsControl this is just a ContentPresenter, in case of ListBox or ComboBox it’s a ListBoxItem or ComboBoxItem respectively; both descendents of ContentControl.

What some people seem to forget is the fact that the ItemsControl sets the value of the wrapper’s DataContext property to the data item itself. Without this the use of datatemplates would not have been possible, because it’s the DataContext that is inherited from the wrapper down to every element inside the datatemplate!


Now this DataContext inheritance is also the solution to a fairly common question on the WPF forums. For example, you want a delete-button in your datatemplate to give the user on every item the option to delete that item. In your click-event handler (or better, a command handler) you need access to the data item that should be deleted. The ‘sender’ parameter in the handler will be equivalent with the Button element, because that’s the element that you clicked. So how to get to the data item? You’ll probably know by now that you can find it in the DataContext property of the ‘sender’! Just cast ‘sender’ back to a Button (or just a FrameworkElement) and cast the value of its DataContext property to your data item!

private void DelButton_Click(object sender, RoutedEventArgs e)
    Button delButton = sender as Button;
    Person person = delButton.DataContext as Person;

If you want to take a look at the testproject, please make sure to rename its extension to .zip.

Categories: Beginner Tags: , ,