views:

29

answers:

1

Hi,

I have TreeView with hierarchical data binding. I want to get TreeViewItem.Header controls not my MVVM. I can get TreeViewItem using TreeView.ItemContainerGenerator.ContainerFromIndex() method... but how to get TreeViewItem.Header ?

Regards, Marcin

A: 

It is very simple:

var item = TreeView.ItemContainerGenerator.ContainerFromIndex(...);
var header = ((TreeViewItem)item).Header;

However it may not be a good idea: Generally any code that requires access to the header control itself (as opposed to the model) is poorly written and should be rewritten to use data binding instead.

Ray Burns
Thanks. But header contains my model not controls. I need controls, because I must change one value of control. Why I don't want to change model? Because I need functionality that is control wide, not model wide. This functionality is in place editing of TreeViewItem.Header text, I must swap TextBlock to TextBox control.
zielu1
You can swap a TextBlock with a TextBox using data binding in many ways. Generally I just have a flag such as "InPlaceEditing" in my view model, and use a data trigger in your template to swap the TextBlock for the TextBox. A couple of other solutions I've used are: 1. Use an attached property to automatically swap the template, which was good for changing a whole UI at once, and 2. Use a binding with a converter to set the control's Template. WPF has so many powerful mechanisms for controlling this via data binding it would almost be a crime to not to use them.
Ray Burns