WPF:数据绑定的TreeViewItem->先前选择了运行时间较长的另一个节点时,不需要选择悬停的节点

时间:2019-01-16 11:03:42

标签: c# wpf mvvm treeview

简而言之:

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

长版:

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

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

  • PreviewMouseRightButtonDown
  • PreviewMouseRightButtonUp
  • PreviewMouseLeftButtonDown
  • PreviewMouseLeftButtonUp
  • PreviewMouseMove
  • 拖放

所有命令均成功触发。这是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:

  • 已启用
  • AllowDrop
  • 已展开
  • 已选择
  • 标签

这是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. 尽管已绑定到TreeViewItem的IsSelected,但并非始终设置ViewModel中的IsSelected
  2. 如果在另一个节点的操作仍在运行时将鼠标移到另一个节点上,则选择将更改为选择悬停的节点,而无需执行任何操作。为什么会这样?

我尝试过的一些事情:

  1. 如果尚未设置,则手动设置IsSelected-可以,但是不必这样做。
  2. 通过调试并查看IsSelected更改时的调用堆栈,我发现WPF似乎在另一个节点获得焦点时触发Select和ChangeSelection –但是为什么呢? …我该如何抑制呢?
  3. 与TreeViewItem.GotFocus事件一起玩,以防止意外选择

在无意设置IsSelected的情况下,这是调用堆栈的一部分。在调用OnGotFocus之后,WPF似乎触发了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
...

1 个答案:

答案 0 :(得分:0)

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

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

我要做的是向MainViewModel引入一个布尔值DisableAutoSelection,然后如果DisableAutoSelection为true,则阻止TreeNodeViewModel中IsSelected值的更新。

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

Voila,现在可以使用,并且随机选择的节点的时间已过:-)