- 创建一个新的 WPF 应用程序
- 在主窗口中放置一个名为“tree1”的树视图
- 复制粘贴下面的代码以查看它的运行情况
基本上,您需要继承TreeViewItem
并构建一种机制来跟踪哪些处理程序被添加到哪个节点:event
不幸的是,没有关于已注册处理程序的信息供您检索。
您还需要完全依赖新的继承来构建节点,以使事情正常工作。这意味着,您不能再引用TreeViewItem
,而必须引用TreeNode
(这是我为自定义类选择的名称,请随意更改)。
承诺的代码如下,它所做的是将“rootNode”节点添加到树中,在扩展时将创建一个兄弟节点,该节点会将相同的处理程序带到自身(因此它也会在扩展时创建一个兄弟节点,并且很快)。
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TreeNode root = new TreeNode();
root.Header = "root";
tree1.Items.Clear();
// add node to tree before adding handlers, or you'll get
// a StackOverflowException
tree1.Items.Add(root);
root.AddHandler(TreeNode.ExpandedEvent, new RoutedEventHandler(expandedHandler));
}
private void expandedHandler(object sender, RoutedEventArgs e) { newNodeCopyExpandedHandlers(sender as TreeNode); }
private void newNodeCopyExpandedHandlers(TreeNode node)
{
TreeNode newNode = new TreeNode();
newNode.Header = "nuovo!";
// add node to tree before adding handlers, or you'll get
// a StackOverflowException
tree1.Items.Add(newNode);
foreach (Delegate d in newNode.GetHandlers(node, TreeNode.ExpandedEvent))
newNode.AddHandler(TreeNode.ExpandedEvent, d);
}
}
public class TreeNode : TreeViewItem
{
private Dictionary<RoutedEvent, List<Delegate>> handlersList = new Dictionary<RoutedEvent, List<Delegate>>();
public new void AddHandler(RoutedEvent e, Delegate d)
{
if (!handlersList.ContainsKey(e)) handlersList.Add(e, new List<Delegate>());
handlersList[e].Add(d);
base.AddHandler(e, d);
}
public new void RemoveHandler(RoutedEvent e, Delegate d)
{
if (!handlersList.ContainsKey(e)) handlersList.Add(e, new List<Delegate>());
if (handlersList[e].Contains(d)) handlersList[e].Remove(d);
base.RemoveHandler(e, d);
}
public List<Delegate> GetHandlers(TreeNode n, RoutedEvent e)
{
if (n.handlersList.ContainsKey(e)) return n.handlersList[e];
else return null;
}
}
}