Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
yangf85 opened this issue Mar 10, 2023 · 1 comment
Open

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

yangf85 opened this issue Mar 10, 2023 · 1 comment

Comments

@yangf85
Copy link

yangf85 commented Mar 10, 2023

No description provided.

@Hakoyu
Copy link

Hakoyu commented Aug 14, 2023

我写到这里 去看了一眼 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}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants