Bind TreeViewItem to property of object
I have a TreeView control with such bindings:
<TreeView ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type Trees:ItemTreeNode}"
ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal" Tag="">
<Image VerticalAlignment="Center" Margin="0,0,4,0" Source="{Binding Path=Icon}" />
<TextBlock VerticalAlignment="Center" Text="{Binding Path=Text}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
And I have next class:
public class ItemTreeNode : INotifyPropertyChanged
{
public event PropertyChangedEventHandler Propert开发者_如何学CyChanged;
public ObservableCollection<ItemTreeNode> Children { get; set; }
public ImageSource Icon {get; set;}
public string Text {get; set;}
public TreeViewItem VisualItem { get; set; }
}
Is it possible to bind a TreeViewItem reference to VisualItem, so I can get TreeViewItem through addressing via VisualItem?
You can try but you would receive a binding error because the TreeView items are of your ItemsSourceCollection type not of type TreeViewItem.
So setup an ItemTreeNode public property to bind SelectedItem to. Then, in the SelectedItemChanged event of your tree, grab the TreeViewItem by using the ItemContainerGenerator.ContainerFromItem method as such:
var tvi = myTreeView.ItemContainerGenerator.ContainerFromItem(selectedItem) as TreeViewItem;
精彩评论