.选择“不更新视图模型对象的可观察集合”

本文关键字:观察 集合 对象 模型 更新 新视图 选择 | 更新日期: 2023-09-27 18:35:45

我有一个类型为 FilterableListItemObservableCollection(如下),我进行以下查询,

this.Gears.Select(r => r.IsAvailible = r.Value == "X6");

但它不会更新列表中的任何项目。如何使选择语句更新列表?

public class FilterableListItem : ViewModelBase
{
    private string value;
    private bool isAvailible;
    public string Value
    {
        get
        {
            return this.value;
        }
        set
        {
            this.value = value;
            this.OnPropertyChanged("Value");
        }
    }
    public bool IsAvailible
    {
        get
        {
            return this.isAvailible;
        }
        set
        {
            if (value != this.isAvailible)
            {
                this.isAvailible = value;
                this.OnPropertyChanged("IsVisible");
            }
        }
    }
    public override string ToString()
    {
        return this.Value;
    }
}

.选择“不更新视图模型对象的可观察集合”

正如我的评论中提到的,Select不应该用于更新你的对象,而应该用来投影你集合中的每个元素。

事实上,您应该使用标准foreach来更新对象:

foreach (var item in Gears)
    item.IsAvailable = (r.Value == "X6");

这将相应地更新您的项目。

尝试使用:

foreach (var r in this.Gears) r.IsAvailible = r.Value == "X6";

.Select 不会更新对象,而是返回已修改对象的 IEnumerable。试试这个:

this.Gears = new ObesrvableCollection<FilterableListItem>(this.Gears.Select(r => r.IsAvailible = r.Value == "X6"));