首页 > 解决方案 > WPF:数据绑定 TreeViewItem -> 当先前选择另一个具有长时间运行操作的节点时,不需要选择悬停节点

问题描述

简而言之:

TreeView 绑定到 ViewModels 的 ObservableCollection。单击具有长时间操作的节点并在操作持续时在其他节点上移动鼠标,导致意外选择悬停的节点(WPF 会这样做,用户没有鼠标单击)。-> 为什么,我该如何阻止呢?

长版:

我有一个 TreeView,其 Hierarchical-DataTemplate 绑定到自定义 ViewModel 的 ObservableCollection。构建节点结构以及运行大多数命令都可以正常工作。

以下是使用 EventToCommandBehaviour 绑定到 ViewModel 中命令的 DataTemplate-Items 的事件:

所有命令都成功触发。这是 XAML 数据模板:

<DataTemplate DataType="{x:Type model:TreeNodeBaseViewModel}">
    <StackPanel Orientation="Horizontal" Height="16">
        <StackPanel Orientation="Horizontal" Height="16" ToolTip="{Binding ToolTip}" IsHitTestVisible="True" Background="Transparent">
            <Grid Height="16" Width="16" Margin="0,0,5,0" Visibility="{Binding ShowIcon, Converter={StaticResource BooleanToVisibilityConverter}, UpdateSourceTrigger=PropertyChanged}">
                <Viewbox Width="{Binding PackIcon.Width}" Height="{Binding PackIcon.Height}">
                    <iconPacks:PackIconSimpleIcons  Foreground="{Binding PackIcon.Color}" Rotation="{Binding PackIcon.Vector_Angle}" HorizontalAlignment="Center" VerticalAlignment="Center" Kind="{Binding PackIcon.Value, Mode=OneWay}" />
                </Viewbox>
            </Grid>
            <Label Content="{Binding DisplayName}" AllowDrop="{Binding IsDropAllowed}" Foreground="{Binding Color}" Padding="0"/>
            <i:Interaction.Behaviors>
                <beh:EventToCommandBehavior Command="{Binding PreviewMouseRightButtonDownCommand}" Event="PreviewMouseRightButtonDown" PassArguments="True" />
                <beh:EventToCommandBehavior Command="{Binding PreviewMouseRightButtonUpCommand}" Event="PreviewMouseRightButtonUp" PassArguments="True" />
                <beh:EventToCommandBehavior Command="{Binding PreviewMouseLeftButtonDownCommand}" Event="PreviewMouseLeftButtonDown" PassArguments="True" />
                <beh:EventToCommandBehavior Command="{Binding PreviewMouseLeftButtonUpCommand}" Event="PreviewMouseLeftButtonUp" PassArguments="True" />
                <beh:EventToCommandBehavior Command="{Binding PreviewMouseMoveCommand}" Event="PreviewMouseMove" PassArguments="True" />
                <beh:EventToCommandBehavior Command="{Binding DropCommand}" Event="Drop" PassArguments="True" />
            </i:Interaction.Behaviors>
        </StackPanel>
        <Button Background="Transparent" BorderThickness="0" Margin="5,0,0,0" Visibility="{Binding IsNodePropertyButtonVisible, Converter={StaticResource BooleanToVisibilityConverter}}">
            <iconPacks:PackIconMaterial  Width="10" Height="10" Foreground="LightGray" HorizontalAlignment="Center" VerticalAlignment="Center" Kind="InformationOutline" />
            <i:Interaction.Behaviors>
                <beh:EventToCommandBehavior Command="{Binding PropertiesCommand}" Event="Click" PassArguments="True" />
            </i:Interaction.Behaviors>
        </Button>
    </StackPanel>
</DataTemplate>

以下 TreeViewItem 属性也绑定到 ViewModel:

这是 XAML:

<Style x:Key="MenuItemTemplateItemContainerStyle" TargetType="{x:Type TreeViewItem}">
    <Setter Property="ContextMenu" Value="{DynamicResource MenuItemContextMenu}"/>
    <Setter Property="IsEnabled" Value="{Binding IsEnabled, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
    <Setter Property="AllowDrop" Value="{Binding IsDropAllowed, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
    <Setter Property="IsSelected" Value="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
    <Setter Property="Tag" Value="{Binding}"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsVisible}" Value="False">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
        <Trigger Property="beh:TreeNodeMouseOver.IsMouseDirectlyOverItem" Value="True">
            <Setter Property="Background" Value="AliceBlue" />
        </Trigger>
    </Style.Triggers>
</Style>

我的问题是:

当我左键单击触发更长运行操作的节点时,会发生两件事:

  1. ViewModel 中的 IsSelected 并不总是设置,虽然它绑定到 TreeViewItem 的 IsSelected
  2. 如果我在另一个节点的操作仍在运行时将鼠标移动到另一个节点上,则选择将更改为选择悬停的节点而无需我做任何事情。为什么会这样?

我尝试过的一些事情:

  1. 如果尚未设置 IsSelected,请手动设置 - 工作正常,但不应该这样做。
  2. 通过调试并查看 IsSelected 更改时的调用堆栈,我发现 WPF 似乎在另一个节点获得焦点时触发 Select 和 ChangeSelection - 但为什么呢?……我怎样才能抑制它?
  3. 玩了 TreeViewItem.GotFocus 事件以防止意外选择

这是无意设置 IsSelected 时调用堆栈的一部分。WPF 似乎在调用 OnGotFocus 后触发 Select 和 ChangeSelection:

[Native to Managed Transition]  
[Managed to Native Transition]  
PresentationFramework.dll!MS.Internal.Data.PropertyPathWorker.SetValue(object item, object value)   Unknown
PresentationFramework.dll!MS.Internal.Data.ClrBindingWorker.UpdateValue(object value)   Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpression.UpdateSource(object value = false)  Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.UpdateValue()   Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpression.UpdateOverride()    Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.Update()    Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.ProcessDirty()  Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.Dirty() Unknown
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.SetValue(System.Windows.DependencyObject d, System.Windows.DependencyProperty dp, object value) Unknown
WindowsBase.dll!System.Windows.DependencyObject.SetValueCommon(System.Windows.DependencyProperty dp = {System.Windows.DependencyProperty}, object value = false, System.Windows.PropertyMetadata metadata = {System.Windows.FrameworkPropertyMetadata}, bool coerceWithDeferredReference = false, bool coerceWithCurrentValue = false, System.Windows.OperationType operationType = Unknown, bool isInternal)   Unknown
WindowsBase.dll!System.Windows.DependencyObject.SetValue(System.Windows.DependencyProperty dp, object value)    Unknown
PresentationFramework.dll!System.Windows.Controls.TreeView.ChangeSelection(object data = {HOSEC.UI.Tree.ViewModels.TreeNodeMainNodeViewModel}, System.Windows.Controls.TreeViewItem container = {System.Windows.Controls.TreeViewItem}, bool selected = true)   Unknown
PresentationFramework.dll!System.Windows.Controls.TreeViewItem.Select(bool selected = true) Unknown
PresentationFramework.dll!System.Windows.Controls.TreeViewItem.OnGotFocus(System.Windows.RoutedEventArgs e = {System.Windows.RoutedEventArgs})  Unknown
PresentationCore.dll!System.Windows.UIElement.IsFocused_Changed(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e) Unknown
WindowsBase.dll!System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)  Unknown
PresentationFramework.dll!System.Windows.FrameworkElement.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)    Unknown
WindowsBase.dll!System.Windows.DependencyObject.NotifyPropertyChange(System.Windows.DependencyPropertyChangedEventArgs args)    Unknown
WindowsBase.dll!System.Windows.DependencyObject.UpdateEffectiveValue(System.Windows.EntryIndex entryIndex, System.Windows.DependencyProperty dp = {System.Windows.DependencyProperty}, System.Windows.PropertyMetadata metadata, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry = {System.Windows.EffectiveValueEntry}, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType)    Unknown
WindowsBase.dll!System.Windows.DependencyObject.SetValueCommon(System.Windows.DependencyProperty dp, object value, System.Windows.PropertyMetadata metadata, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType, bool isInternal)    Unknown
WindowsBase.dll!System.Windows.DependencyObject.SetValue(System.Windows.DependencyPropertyKey key, object value)    Unknown
PresentationCore.dll!System.Windows.Input.FocusManager.OnFocusedElementChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)  Unknown
...

标签: c#wpfmvvmtreeview

解决方案


好的,这绝对是奇怪的 WPF 行为,但我现在修复了它:

首先,我停用了除 PreviewMouseLeftButtonDownCommand 之外的所有命令,并发现 TreeView 在长期操作期间失去焦点。当出于某种原因尝试重新获得焦点时,WPF 会将焦点设置为当前悬停的节点 - 这是可重现的并且不需要用户交互。

我所做的是将布尔值 DisableAutoSelection 引入 MainViewModel,然后如果 DisableAutoSelection 为真,则阻止更新 TreeNodeViewModel 中的 IsSelected 值。

此外,我将 TreeNodeViewModel 的 PreviewMouseLeftButtonDownCommand 中的代码移至异步任务,并在运行任务之前设置 DisableAutoSelection = true。等待任务完成时,我设置 DisableAutoSelection = false。

瞧,它现在可以工作了,随机选择节点的时间已经结束:-)


推荐阅读