[英]How can I do this custom Select All function to work?
我有两个连接的课程: 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
class 中添加了另一个属性:
public const string IsSelectPropertyName = "IsSelect";
private bool _isSelect = false;
public bool IsSelect
{
get
{
return _isSelect ;
}
set
{
Set(IsSelectPropertyName, ref _isSelect , value);
}
}
然后是Smartphone
SelectAll
中的 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
class 中使用此 function:
public void CheckSelected()
{
bool isUnchecked = Models.Select(item => item.IsSelect).AsQueryable().All(value => value == false);
if (isUnchecked)
{
SelectAll = false;
} else
{
SelectAll = true;
}
}
但是,如果像这样添加到Model
class 中的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();
}
}
}
我收到如下错误:
堆栈溢出异常
问题是当您在循环中调用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();
call 未执行,“打破”循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.