首先为TreeView控件制作一个Style:
<Style x:Key="LibraryTreeViewItemStyle" TargetType="{x:Type TreeViewItem}"
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight" Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
<TreeView ItemsSource="{Bind Path=YourCollection}" ItemContainerStyle="{StaticRecource LibraryTreeViewItemStyle}" ItemTemplate={StaticResource YourHierarchicalDataTemplate} />
最后,只要在绑定的数据类中提供相应的属性就可以,例如:
private bool m_bIsSelected = false;
public bool IsSelected
{
get { return m_bIsSelected; }
set
{
m_bIsSelected = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsSelected"));
}
}
现在只要操作数据类的这个属性就可以控制树视图的选择项了。