Take a look at the TreeView.SelectedItem Property page at MSDN.
You can bind directly to the TreeView.SelectedItem
property:
<TreeView ItemsSource="{Binding Items}" SelectedItem="{Binding Item, Mode=OneWay}" />
Note that the TreeView.SelectedItem
property is only read only, so you must use a OneWay
binding... this means that you cannot set the selected item from your view model. To do that, you will need to create your own two way selected item property using an Attached Property
.
EDIT >>>
My apologies @Scroog1, I normally use an AttachedProperty
to do this. You are right that even with a OneWay
binding, there is an error using this method. Unfortuately, my AttachedProperty
code is long, but there is another way to do this.
I wouldn't necessarily recommend this as it's never really a good idea to put UI properties into your data objects, but if you add an IsSelected
property to your data object, then you can bind it directly to the TreeViewItem.IsSelected
property:
<TreeView ItemsSource="Items" HorizontalAlignment="Stretch" ... Name="MyTreeViewMenu">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
I just searched and found a 'fuller' answer for you in the WPF MVVM TreeView SelectedItem post here on StackOverflow.
Alternatively, there is another way... you could also use the TreeView.SelectedValue
and TreeView.SelectedValuePath
properties. The basic idea is to set the TreeView.SelectedValuePath
property to the name of a property on your data object. When an item is selected, the TreeView.SelectedValue
property will then be set to the value of that property of the selected data item. You can find out more about this method from the How to: Use SelectedValue, SelectedValuePath, and SelectedItem page at MSDN. This generally works best if you have a uniquely identifiable property like an identifier of some kind. This code example is from MSDN:
<TreeView ItemsSource="{Binding Source={StaticResource myEmployeeData},
XPath=EmployeeInfo}" Name="myTreeView" SelectedValuePath="EmployeeNumber" />
<TextBlock Margin="10">SelectedValuePath: </TextBlock>
<TextBlock Margin="10,0,0,0" Text="{Binding ElementName=myTreeView,
Path=SelectedValuePath}" Foreground="Blue"/>
<TextBlock Margin="10">SelectedValue: </TextBlock>
<TextBlock Margin="10,0,0,0" Text="{Binding ElementName=myTreeView,
Path=SelectedValue}" Foreground="Blue"/>