gpt4 book ai didi

wpf - 为什么 e.Source 依赖于 TreeView 填充方法?

转载 作者:行者123 更新时间:2023-12-01 09:11:34 27 4
gpt4 key购买 nike

我有两棵树:

  1. fooTree - 由元素组成,
  2. barTree - 由
  3. 构建

两棵树都有 MouseRightButtonDown 事件,但 e.Source 类型不同:

  1. fooTree - System.Windows.Controls.TreeViewItem
  2. barTree - System.Windows.Controls.TreeView

为什么 e.Source 不同?另外,如何获取 barTree 的点击项?

标记:

    <TreeView Name="fooTree" MouseRightButtonDown="fooTree_MouseDown">
<TreeViewItem Header="foo"></TreeViewItem>
<TreeViewItem Header="foo"></TreeViewItem>
</TreeView>

<TreeView Name="barTree" MouseRightButtonDown="barTree_MouseDown" ItemsSource="{Binding BarItems}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>

代码:

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = this;
}

public string[] BarItems
{
get { return new string[] { "bar", "bar" }; }
}

private void barTree_MouseDown(object sender, MouseButtonEventArgs e)
{
}

private void fooTree_MouseDown(object sender, MouseButtonEventArgs e)
{
}
}

最佳答案

不知道为什么会这样,但至少我找到了解决办法:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f0d3af69-6ecc-4ddb-9526-588b72d5196b/

  1. If your handler is on the TreeView, use the OriginalSource property in the event arguments and walk up the visual parent chain until you find a TreeViewItem. Then, select it. You can walk the visual parent chain by using System.Windows.Media.VisualTreeHelper.GetParent.

  2. You could try registering a class handler for type TreeViewItem and the mouse down event. Then, your handler should only be called when mouse events pass through TreeViewItem elements.

  3. You could register a class handler for type TreeViewItem and the context menu opening event.

所以我的代码是:

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

static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
{
while (source != null && source.GetType() != typeof(T))
source = VisualTreeHelper.GetParent(source);

return source;
}

关于wpf - 为什么 e.Source 依赖于 TreeView 填充方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/593194/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com