实现 WPF 树视图会使用大量 XAML,因此此答案仅包含代码片段。
我的目标是单击左窗格中的选定树视图项目并刷新右窗格中的项目(如 Windows 资源管理器)。
为了使选择选定的树视图项起作用,我在我的 ViewModel 中的以下 XAML 示例中实现了两个事件:
- OnItemSelected 使用事件 TreeViewItem.Selected
- MouseLeftButtonUp 使用事件 TreeViewItem.MouseLeftButtonUp
当我的 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;
}
}
}