Tuesday, June 15, 2010

Getting control information from DataTemplate in ItemsControl

Sometimes we use ItemsControl to show a list of data when we don't want the added features provided by its various subclasses. But the problem is when we use data templates with ItemsControl. It seems impossible to get the info about the control and all information it provides seems to be about the data object it is mapped to, even when we have used specific user control in data template. It is generally required to get the information about this control to do some other things with this, like calling another method, use a property etc. Let's discuss how can we get that.


We create a Student class with two properties: StudentID and StudentName.



Now we create a user control with name StudentView with following XAML code:

The code behind of the control is as follows: (Please notice notifyMe method added)



Now we create ViewModel of the CourseView. We need to display a list of Students in CourseView. The definition of CourseViewModel is as follows: (Here we have created an observable collection of Students.)



Now comes the real CourseView. You might notice the ItemsControl. In ItemsControl, we have created a DataTemplate to show the information about different Student objects by using StudentView user control. We have also created a button. We will be using Click event of this button to get information about the elements in ItemsControl.


Now comes the real CourseView. You might notice the ItemsControl. In ItemsControl, we have created a DataTemplate to show the information about different Student objects by using StudentView user control. In the CourseView constructor, we have instantiated our ViewModel. I am in no way suggesting that this is the best approach for interaction between your views and view models but to keep the length of this discussion limited, I want to keep it direct. The interesting part is Button_Click (click event of the button in CourseView). You can see that we have iterated through the elements of myStudents ItemsControl. To get the information about the control, we have to use VisualTreeHelper. There is one important thing, you must be familiar with the visual hierarchy of the view, which generally is not an issue.



No comments: