在树视图中突出显示多个选定的子节点

时间:2018-04-15 08:47:23

标签: .net wpf xaml mvvm treeview

我试图在树视图中选择多个子项。所有子节点都绑定了一组自定义类对象,即View.cs.请注意,treeview没有树视图项,而是与其链接的自定义类。

以下代码用于执行多个节点选择,它工作得很好(我通过调试检查了它)。但它并没有突出显示UI上多个选定的子节点。 我需要视觉反馈,以便用户知道他选择了多少个节点。我不确定如何修复它,会感激任何帮助。

    List<View> selectedViewItems = new List<View>();

    private static readonly PropertyInfo IsSelectionChangeActiveProperty = typeof(TreeView).GetProperty(
        "IsSelectionChangeActive",
        BindingFlags.NonPublic | BindingFlags.Instance
    );

    public static void AllowMultiSelection(TreeView treeView)
    {
        if (IsSelectionChangeActiveProperty == null) return;

        SelectMultipleItemsOnTreeView(treeView, SheetManagerUserControl.Instance.selectedViewItems);
    }

    private static void SelectMultipleItemsOnTreeView(TreeView treeView, List<View> selectedItems)
    {
        treeView.SelectedItemChanged += (a, b) =>
        {
            var treeViewItem = treeView.SelectedItem as View;

            if (treeViewItem == null) return;

            // allow multiple selection 
            // when key key is pressed 
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                // delete selection change notification 
                // select all items 
                // restore 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);
            }
        };
    }

0 个答案:

没有答案