<TreeView x:Name="CustomTreeView"
Canvas.Top="1" Canvas.Bottom="1" VerticalAlignment="Stretch"
Margin="10,45,10,10"
MouseRightButtonDown="TView_MouseRightButtonDown">
//添加事件
private void TView_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
object item = GetElementFromPoint((ItemsControl)sender, e.GetPosition((ItemsControl)sender));
isItemSelected = (item != null);
if (!isItemSelected)
{
this.CustomTreeView.ContextMenu = null;
}
}
//根据焦点判断是否有选中对象
private object GetElementFromPoint(ItemsControl itemsControl, Point point)
{
UIElement element = itemsControl.InputHitTest(point) as UIElement;
while (element != null)
{
if (element == itemsControl)
return null;
object item = itemsControl.ItemContainerGenerator.ItemFromContainer(element);
if (!item.Equals(DependencyProperty.UnsetValue))
return item;
element = (UIElement)VisualTreeHelper.GetParent(element);
}
return null;
}
标签:itemsControl,null,return,object,element,item,右键,wpf,TreeView From: https://www.cnblogs.com/xfn1688/p/16999974.html