程序员人生 网站导航

TreeView下右击选中节点

栏目:综合技术时间:2014-03-15 08:57:13
在TreeView中右击节点,selectNode不是右击的节点,需要另外一个事件绑定:

在.net2.0中可以使用:

方法一:在TreeView中加MouseDown事件

private void tvwZD_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode CurrentNode = tvwZD.GetNodeAt(ClickPoint);
tvwZD.SelectedNode = CurrentNode;
}
}
方法二:在TreeView中加NodeMouseClick事件
private void tvwZD_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeView tn = (TreeView)sender;
if (e.Button == MouseButtons.Right)
{
tn.SelectedNode = e.Node;
}
}

在WPF 中.Net3.0 3.5以上用

在TreeViewItem中响应PreviewMouseRightButtonDown事件

private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
if (treeViewItem != null)
{
treeViewItem.Focus();
e.Handled = true;
}
}

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

return source; 
}
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐