【问题标题】:How can I do this custom Select All function to work?我怎样才能使这个自定义的全选功能起作用?
【发布时间】:2020-06-01 11:15:51
【问题描述】:

我有两个连接的类:Smartphone 和 Model。 Smartphone 包含 Model 的集合,如下所示:

public class Smartphone
{
    public string BrandName { get; set; }
    public ObservableCollection<Model> Models { get; set; } = new ObservableCollection<Model>();
}

而Model:

public class Smartphone
{
    public string ModelName { get; set; }
}

然后我在Model 类中添加了另一个属性:

public const string IsSelectPropertyName = "IsSelect";

private bool _isSelect = false;

public bool IsSelect
{
    get
    {
        return _isSelect ;
    }
    set
    {
        Set(IsSelectPropertyName, ref _isSelect , value);
    }
}

然后是Smartphone 类中的SelectAll:

private bool _selectAll;

public bool SelectAll
{
    get
    {
        return _selectAll;
    }
    set
    {
        _selectAll = value;
        foreach (var item in Models)
        {
            item.IsSelect = value;
        }
        Set(() => SelectAll, ref _selectAll, value);
    }
}

这里的问题是,如果一项未被选中,SelectAll 仍然被选中。到目前为止,我尝试的是在 Smartphone 类中使用此功能:

public void CheckSelected()
{
    bool isUnchecked = Models.Select(item => item.IsSelect).AsQueryable().All(value => value == false);

    if (isUnchecked)
    {
        SelectAll = false;
    } else
    {
        SelectAll = true;
    }
}

但是,如果像这样添加到Model 类中的IsSelect 属性中:

public const string IsSelectPropertyName = "IsSelect";

private bool _isSelect = false;

public bool IsSelect
{
    get
    {
        return _isSelect ;
    }
    set
    {
        Set(IsSelectPropertyName, ref _isSelect , value);
        if (Smartphone != null)
        {
            Smartphone.CheckSelected();
        }
    }
}

我收到如下错误:

堆栈溢出异常

【问题讨论】:

    标签: c# mvvm-light


    【解决方案1】:

    问题在于,当您在循环中调用 CheckSelect() -> SelectAll -> IsSelect -> CheckSelect() 时,您一直在使用 SelectAll 和 IsSelect 设置器。

    一种可能的解决方案是仅在值实际更改时才在属性的设置器中做出反应。代码可能如下所示:

    get
    {
        return _isSelect ;
    }
    set
    {
        if (_isSelect == value)
            return; // don't do anything, nothing has been changed
        Set(IsSelectPropertyName, ref _isSelect , value);
        if (Smartphone != null)
        {
            Smartphone.CheckSelected();
        }
    }
    

    您将第一次进入 setter,但在第二次时,字段 _isSelect 已更改,您使用 if() 正文中的 return 语句退出 setter。这也意味着不会执行以下Smartphone.CheckSelected(); 调用,“中断”循环。

    【讨论】:

    • 感谢您的回答。虽然这消除了错误问题,但这也使我的SelectAll 不再工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2013-07-21
    • 1970-01-01
    • 2012-04-15
    • 2016-08-28
    • 1970-01-01
    相关资源
    最近更新 更多