The standard WPF tree view does not support multiple selections.
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)
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);
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With