我该如何执行此自定义全选功能?

问题描述 投票:0回答:1

我有两个连接的类:SmartphoneModelSmartphone包含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);
    }
}

然后是SelectAll类中的Smartphone

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;
    }
}

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

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();
        }
    }
}

我有类似的错误:

StackoverflowException

c# mvvm-light
1个回答
0
投票

[问题是,当您循环调用SelectAll-> IsSelect-> CheckSelect()-> SelectAll时,总是会进入IsSelectCheckSelect()设置器。

一种可能的解决方案是仅在实际更改了值的情况下,才对属性的设置器做出反应。代码可能看起来像这样:

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();
    }
}

您将第一次进入设置器,但是第二次更改字段_isSelect,并使用return正文中的if()语句退出设置器。这也意味着未执行以下Smartphone.CheckSelected();调用,“中断”了循环。

© www.soinside.com 2019 - 2024. All rights reserved.