實現一個WPF樹視圖使用大量的XAML,所以這個答案只包含代碼片段。
我的目標是單擊左窗格中選定的樹視圖項目並刷新右窗格(如Windows資源管理器)中的項目。
要選擇被選中的TreeView項工作中,我實現了兩個事件在我的視圖模型下面的XAML代碼示例:
- 使用事件TreeViewItem.Selected
- 的MouseLeftButtonUp使用事件TreeViewItem.MouseLeftButtonUp
OnItemSelected
當我的MouseLeftButtonUp事件觸發時,請確保指示我使用以下事件處理事件:
這裏是XAML
<TreeView Name="MyTreeView"
ItemsSource="{Binding Collections}"
Margin="0"
Grid.Row="0"
TreeViewItem.Selected="OnItemSelected"
TreeViewItem.Unselected="OnItemUnSelected">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="TreeViewItem.MouseLeftButtonUp" Handler="MouseLeftButtonUp"/>
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</TreeView.ItemContainerStyle>
<!-- other XAML removed for this answer-->
</TreeView>
這裏是事件處理程序
private void OnItemSelected(object sender, RoutedEventArgs e)
{
// do something...
}
// additional info: cannot detect mouse down events; preview mouse events also work
private void MouseLeftButtonUp(object sender, MouseButtonEventArgs args)
{
TreeViewItem tvi = sender as TreeViewItem;
if (tvi != null)
{
// process folder items
MyViewModel fvm = tvi.Header as MyViewModel;
if (fvm != null)
{
// only process selected treeview items
if (fvm.IsSelected)
{
fvm.IsSelected = true;
// prevent bubbling once we find the selected tree view item
args.Handled = true;
}
}
}