具有多个选择的WPF TreeView [英] WPF TreeView with Multiple Selection
本文介绍了具有多个选择的WPF TreeView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标准WPF 树视图可以不支持多项选择.
The standard WPF tree view does not support multiple selections.
如何向WPF应用程序添加支持多重选择的树形视图?商业产品很好(我目前知道一种商业实现方式- http://www.telerik .com/products/wpf/treeview.aspx )
How can I add a tree view that supports multiple selection to my WPF application? Commercial products are fine (I am currently aware of one commercial implementation - http://www.telerik.com/products/wpf/treeview.aspx)
推荐答案
下面的代码可以正常工作,并且更简单.但是,缺点是要使用treeview类的非公共属性IsSelectionChangeActive.下面的代码:
The code below works fine and is much simpler. However the draw back is the use of the non public property, IsSelectionChangeActive, of the treeview class. Code below:
private static readonly PropertyInfo IsSelectionChangeActiveProperty
= typeof (TreeView).GetProperty
(
"IsSelectionChangeActive",
BindingFlags.NonPublic | BindingFlags.Instance
);
public static void AllowMultiSelection(TreeView treeView)
{
if (IsSelectionChangeActiveProperty==null) return;
var selectedItems = new List<TreeViewItem>();
treeView.SelectedItemChanged += (a, b) =>
{
var treeViewItem = treeView.SelectedItem as TreeViewItem;
if (treeViewItem == null) return;
// allow multiple selection
// when control key is pressed
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
// suppress selection change notification
// select all selected items
// then restore selection change notifications
var isSelectionChangeActive =
IsSelectionChangeActiveProperty.GetValue(treeView, null);
IsSelectionChangeActiveProperty.SetValue(treeView, true, null);
selectedItems.ForEach(item => item.IsSelected = true);
IsSelectionChangeActiveProperty.SetValue
(
treeView,
isSelectionChangeActive,
null
);
}
else
{
// deselect all selected items except the current one
selectedItems.ForEach(item => item.IsSelected = (item == treeViewItem) );
selectedItems.Clear();
}
if (!selectedItems.Contains(treeViewItem))
{
selectedItems.Add(treeViewItem);
}
else
{
// deselect if already selected
treeViewItem.IsSelected = false;
selectedItems.Remove(treeViewItem);
}
};
}
这篇关于具有多个选择的WPF TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文