0

我正面临 MudSelect 的问题MultiSelect="true"。即使它设置了选定的值,它也不会检查选定的值:

<MudSelect Label="Select Item" SelectAll="true" MultiSelection="true" SelectedValues="@SelectedTestItems" T="@MultiSelectItem" ToStringFunc="@ToString">
    @foreach (MultiSelectItem item in AllItems)
    {
        <MudSelectItem Value="@item" />
    }
</MudSelect>

@code {
    private List<MultiSelectItem> SelectedTestItems = new() {
        new MultiSelectItem{Id = 1, Name = "Test 1"},
    };

    private List<MultiSelectItem> AllItems = new() {
        new MultiSelectItem{Id = 1, Name = "Test 1"},
        new MultiSelectItem{Id = 2, Name = "Test 2"},
        new MultiSelectItem{Id = 3, Name = "Test 3"},
        new MultiSelectItem{Id = 4, Name = "Test 4"},
    };

    private string ToString(MultiSelectItem x)
        => x is null ? string.Empty : $"{x.Name}";

    public class MultiSelectItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
} 

我还发布了@github 的详细信息:https ://github.com/MudBlazor/MudBlazor/discussions/3532 。

4

1 回答 1

0

您的问题是您没有覆盖相等比较的必要方法。这是基于您的代码片段的解决方案,您可以在线使用它:https ://try.mudblazor.com/snippet/wYwPbGvKRlGThZsa

MudSelect 在内部使用 HashSet,因此当您使用自定义引用类型作为值时,您必须确保它们具有GetHashCodeEquals基于它们的数据:

<MudSelect Label="Select Item" SelectAll="true" MultiSelection="true" SelectedValues="@SelectedTestItems" T="@MultiSelectItem" ToStringFunc="@ToString">
    @foreach (MultiSelectItem item in AllItems)
    {
        <MudSelectItem Value="@item" />
    }
</MudSelect>

@code {
    private List<MultiSelectItem> SelectedTestItems = new() {
        new MultiSelectItem{Id = 1, Name = "Test 1"},
    };

    private List<MultiSelectItem> AllItems = new() {
        new MultiSelectItem{Id = 1, Name = "Test 1"},
        new MultiSelectItem{Id = 2, Name = "Test 2"},
        new MultiSelectItem{Id = 3, Name = "Test 3"},
        new MultiSelectItem{Id = 4, Name = "Test 4"},
    };

    private string ToString(MultiSelectItem x)
        => x is null ? string.Empty : $"{x.Name}";

    public class MultiSelectItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public override bool Equals(object o) {
            var other = o as MultiSelectItem;
            return other?.Id==Id;
        }
        public override int GetHashCode() => Id.GetHashCode();
    }


}
于 2021-12-16T08:45:21.807 回答