在显示ContextMenu之前,右键单击选择TreeView节点

时间:2009-02-26 20:49:14

标签: wpf treeview contextmenu

我想在显示ContextMenu之前右键单击选择一个WPF TreeView节点。

对于WinForms,我可以使用像Find node clicked under context menu这样的代码,什么是WPF替代品?

11 个答案:

答案 0 :(得分:126)

取决于树的填充方式,the sender and the e.Source values may vary

其中一个可能的解决方案是使用e.OriginalSource并使用VisualTreeHelper查找TreeViewItem:

private void OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TreeViewItem treeViewItem = VisualUpwardSearch(e.OriginalSource as DependencyObject);

    if (treeViewItem != null)
    {
        treeViewItem.Focus();
        e.Handled = true;
    }
}

static TreeViewItem VisualUpwardSearch(DependencyObject source)
{
    while (source != null && !(source is TreeViewItem))
        source = VisualTreeHelper.GetParent(source);

    return source as TreeViewItem;
}

答案 1 :(得分:20)

如果您想要一个仅限XAML的解决方案,您可以使用Blend Interactivity。

假设TreeView是绑定到具有Boolean属性IsSelected属性StringName属性Children的视图模型的分层集合的数据,以及一组名为<TreeView ItemsSource="{Binding Items}"> <TreeView.ItemContainerStyle> <Style TargetType="TreeViewItem"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/> </Style> </TreeView.ItemContainerStyle> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Children}"> <TextBlock Text="{Binding Name}"> <i:Interaction.Triggers> <i:EventTrigger EventName="PreviewMouseRightButtonDown"> <ei:ChangePropertyAction PropertyName="IsSelected" Value="true" TargetObject="{Binding}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 的子项目。

TreeViewItem.IsSelected

有两个有趣的部分:

  1. IsSelected属性绑定到视图模型上的IsSelected属性。将view-model上的PreviewMouseRightButtonDown属性设置为true将选择树中的相应节点。

  2. TextBlock在节点的可视部分触发时(在此示例中为IsSelected),视图模型上的{{1}}属性设置为true。返回1.您可以看到树中单击的相应节点成为选定节点。

  3. 在项目中获得Blend Interactivity的一种方法是使用NuGet包Unofficial.Blend.Interactivity

答案 2 :(得分:16)

使用“item.Focus();”似乎没有100%工作,使用“item.IsSelected = true;”确实

答案 3 :(得分:12)

使用alex2k8的原创想法,正确处理Wieser Software Ltd的非视觉效果,Stefan的XAML,Erlend的IsSelected,以及我对真正制作静态方法的贡献Generic:

XAML:

<TreeView.ItemContainerStyle> 
    <Style TargetType="{x:Type TreeViewItem}"> 
        <!-- We have to select the item which is right-clicked on --> 
        <EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown"
                     Handler="TreeViewItem_PreviewMouseRightButtonDown"/> 
    </Style> 
</TreeView.ItemContainerStyle>

C#代码背后:

void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TreeViewItem treeViewItem = 
              VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject);

    if(treeViewItem != null)
    {
        treeViewItem.IsSelected = true;
        e.Handled = true;
    }
}

static T VisualUpwardSearch<T>(DependencyObject source) where T : DependencyObject
{
    DependencyObject returnVal = source;

    while(returnVal != null && !(returnVal is T))
    {
        DependencyObject tempReturnVal = null;
        if(returnVal is Visual || returnVal is Visual3D)
        {
            tempReturnVal = VisualTreeHelper.GetParent(returnVal);
        }
        if(tempReturnVal == null)
        {
            returnVal = LogicalTreeHelper.GetParent(returnVal);
        }
        else returnVal = tempReturnVal;
    }

    return returnVal as T;
}

编辑:以前的代码总是适用于这种情况,但在另一种情况下,当LogicalTreeHelper返回一个值时,VisualTreeHelper.GetParent返回null,所以修复了它。

答案 4 :(得分:11)

在XAML中,在XAML中添加PreviewMouseRightButtonDown处理程序:

    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <!-- We have to select the item which is right-clicked on -->
            <EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="TreeViewItem_PreviewMouseRightButtonDown"/>
        </Style>
    </TreeView.ItemContainerStyle>

然后像这样处理事件:

    private void TreeViewItem_PreviewMouseRightButtonDown( object sender, MouseEventArgs e )
    {
        TreeViewItem item = sender as TreeViewItem;
        if ( item != null )
        {
            item.Focus( );
            e.Handled = true;
        }
    }

答案 5 :(得分:7)

Almost Right,但您需要注意树中的非视觉效果(例如Run)。

static DependencyObject VisualUpwardSearch<T>(DependencyObject source) 
{
    while (source != null && source.GetType() != typeof(T))
    {
        if (source is Visual || source is Visual3D)
        {
            source = VisualTreeHelper.GetParent(source);
        }
        else
        {
            source = LogicalTreeHelper.GetParent(source);
        }
    }
    return source; 
}

答案 6 :(得分:6)

我认为注册一个类处理程序应该可以解决问题。 只需在app.xaml.cs代码文件中的TreeViewItem的PreviewMouseRightButtonDownEvent上注册一个路由事件处理程序,如下所示:

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(TreeViewItem), TreeViewItem.PreviewMouseRightButtonDownEvent, new RoutedEventHandler(TreeViewItem_PreviewMouseRightButtonDownEvent));

        base.OnStartup(e);
    }

    private void TreeViewItem_PreviewMouseRightButtonDownEvent(object sender, RoutedEventArgs e)
    {
        (sender as TreeViewItem).IsSelected = true;
    }
}

答案 7 :(得分:1)

我在使用HierarchicalDataTemplate方法选择子项时遇到了问题。如果我选择了节点的子节点,它将以某种方式选择该子节点的根父节点。我发现MouseRightButtonDown事件会在孩子的每个级别被调用。例如,如果你有一个像这样的树:

项目1 - 孩子1 - 孩子2
- Subitem1
- Subitem2

如果我选择了Subitem2,事件将触发三次,并且将选择第1项。我用布尔和异步调用解决了这个问题。

private bool isFirstTime = false;
    protected void TaskTreeView_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        var item = sender as TreeViewItem;
        if (item != null && isFirstTime == false)
        {
            item.Focus();
            isFirstTime = true;
            ResetRightClickAsync();
        }
    }

    private async void ResetRightClickAsync()
    {
        isFirstTime = await SetFirstTimeToFalse();
    }

    private async Task<bool> SetFirstTimeToFalse()
    {
        return await Task.Factory.StartNew(() => { Thread.Sleep(3000); return false; });
    }

感觉有点笨拙,但基本上我在第一次通过时将布尔值设置为true,并在几秒钟内将其重置在另一个线程上(在本例中为3)。这意味着下一次经过它将尝试向上移动树的位置将被跳过,让您选择正确的节点。它似乎工作到目前为止: - )

答案 8 :(得分:1)

使用MVVM解决此问题的另一种方法是使用bind命令右键单击视图模型。在那里,您可以指定其他逻辑以及source.IsSelected = true。 这仅使用xmlns:i="http://schemas.microsoft.com/expression/2010/intera‌​ctivity"中的System.Windows.Interactivity

XAML for view:

<TreeView ItemsSource="{Binding Items}">
  <TreeView.ItemContainerStyle>
    <Style TargetType="TreeViewItem">
      <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
    </Style>
  </TreeView.ItemContainerStyle>
  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
      <TextBlock Text="{Binding Name}">
        <i:Interaction.Triggers>
          <i:EventTrigger EventName="PreviewMouseRightButtonDown">
            <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TreeViewItemRigthClickCommand}" CommandParameter="{Binding}" />
          </i:EventTrigger>
        </i:Interaction.Triggers>
      </TextBlock>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

查看型号:

    public ICommand TreeViewItemRigthClickCommand
    {
        get
        {
            if (_treeViewItemRigthClickCommand == null)
            {
                _treeViewItemRigthClickCommand = new RelayCommand<object>(TreeViewItemRigthClick);
            }
            return _treeViewItemRigthClickCommand;
        }
    }
    private RelayCommand<object> _treeViewItemRigthClickCommand;

    private void TreeViewItemRigthClick(object sourceItem)
    {
        if (sourceItem is Item)
        {
            (sourceItem as Item).IsSelected = true;
        }
    }

答案 9 :(得分:0)

您可以使用鼠标按下事件选择它。这将在上下文菜单启动之前触发选择。

答案 10 :(得分:0)

如果要保留在MVVM模式中,可以执行以下操作:

查看:

<TreeView x:Name="trvName" ItemsSource="{Binding RootElementListView}" Tag="{Binding ClickedTreeElement, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type models:YourTreeElementClass}" ItemsSource="{Binding Path=Subreports}">
            <TextBlock Text="{Binding YourTreeElementDisplayProperty}" PreviewMouseRightButtonDown="TreeView_PreviewMouseRightButtonDown"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

后面的代码:

private void TreeView_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    if (sender is TextBlock tb && tb.DataContext is YourTreeElementClass te)
    {
        trvName.Tag = te;
    }
}

ViewModel:

private YourTreeElementClass _clickedTreeElement;

public YourTreeElementClass ClickedTreeElement
{
    get => _clickedTreeElement;
    set => SetProperty(ref _clickedTreeElement, value);
}

现在,您可以对ClickedTreeElement属性的更改做出反应,也可以使用内部与ClickedTreeElement一起使用的命令。

扩展视图:

<UserControl ...
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <TreeView x:Name="trvName" ItemsSource="{Binding RootElementListView}" Tag="{Binding ClickedTreeElement, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseRightButtonUp">
                <i:InvokeCommandAction Command="{Binding HandleRightClickCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type models:YourTreeElementClass}" ItemsSource="{Binding Path=Subreports}">
                <TextBlock Text="{Binding YourTreeElementDisplayProperty}" PreviewMouseRightButtonDown="TreeView_PreviewMouseRightButtonDown"/>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</UserControl>