[英]WPF treeview how to handle mouse clicks in treeview but not on a treeviewitem?
我想知道我該怎么做。 我不能很好地檢查鼠標是否不在item1,item2,...上,可以嗎? 應該有一些更好的方法來做到這一點。 如果用戶單擊非項目空間,我只想取消選擇所有項目。
您可以在Click
處理程序中執行所需的操作,添加以下代碼:
HitTestResult hitTestResult = VisualTreeHelper.HitTest(uiElement, DragStartPosition);
TreeViewItem listBoxItem = hitTestResult.VisualHit.GetParentOfType<TreeViewItem>();
if (listBoxItem == null)
{
// user has clicked, but not on a TreeViewItem
}
GetParentOfType
方法是我創建的擴展方法,如下所示:
public static T GetParentOfType<T>(this DependencyObject element) where T : DependencyObject
{
Type type = typeof(T);
if (element == null) return null;
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent == null && ((FrameworkElement)element).Parent is DependencyObject)
parent = ((FrameworkElement)element).Parent;
if (parent == null) return null;
else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type))
return parent as T;
return GetParentOfType<T>(parent);
}
請注意, 擴展方法需要放置在static
類中……如果願意,您始終可以將其重構為普通方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.