[英]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.