我有两个连接的类: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);
}
}
然后是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
[问题是,当您循环调用SelectAll
-> IsSelect
-> CheckSelect()
-> SelectAll
时,总是会进入IsSelect
和CheckSelect()
设置器。
一种可能的解决方案是仅在实际更改了值的情况下,才对属性的设置器做出反应。代码可能看起来像这样:
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();
调用,“中断”了循环。