Panuon.WPF.UI icon indicating copy to clipboard operation
Panuon.WPF.UI copied to clipboard

ListBoxHelper.SelectedItems 绑定ViewModel属性,一直为null

Open yangf85 opened this issue 2 years ago • 1 comments

yangf85 avatar Mar 10 '23 02:03 yangf85

我写到这里 去看了一眼 Code

确实是不能用 先给一个临时解决方案

public static class ListBoxHelper
{
    public static IList GetSelectedItems(ListBox listBox)
    {
        return (IList)listBox.GetValue(SelectedItemsProperty);
    }

    public static void SetSelectedItems(ListBox listBox, IList value)
    {
        throw new Exception(
            "This property is read-only. To bind to it you must use 'Mode=OneWayToSource'."
        );
    }

    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.RegisterAttached(
            "SelectedItems",
            typeof(IList),
            typeof(ListBoxHelper),
            new FrameworkPropertyMetadata(null, OnSelectedItemsChanged)
        );

    private static void OnSelectedItemsChanged(
        DependencyObject obj,
        DependencyPropertyChangedEventArgs e
    )
    {
        if (obj is not ListBox listBox)
            return;
        InitializeSelectedItems(listBox);
        listBox.SelectionChanged += ListBox_SelectionChanged;

        static void InitializeSelectedItems(ListBox listBox)
        {
            if (GetSelectedItems(listBox) is not IList list)
                return;
            list.Clear();
            foreach (var item in listBox.SelectedItems)
                list.Add(item);
        }
        static void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is not ListBox listBox)
                return;
            if (GetSelectedItems(listBox) is not IList list)
                return;
            foreach (var item in e.RemovedItems)
                list.Remove(item);
            foreach (var item in e.AddedItems)
                list.Add(item);
        }
    }
}

在ViewModel中绑定时要注意 先给绑定值赋值

public IList SelectedItems { get; set; } = new List<MyClass>();
// 也可以使用指定类型
// public List<ListBoxItemVM> SelectedItems { get; set; } = new();
ListBoxHelper.SelectedItems="{Binding SelectedItems}"

Hakoyu avatar Aug 14 '23 12:08 Hakoyu