我认为这应该很简单,但无法相信如何做到。
我尝试在标签中绑定(bind)具有其属性的对象的计数 isWorking
设置为True
这是我的收藏。
public readonly ObservableCollection<ComputerModel.ControleData> _ComputerList =
new ObservableCollection<ComputerModel.ControleData>();
public ObservableCollection<ComputerModel.ControleData> ComputerList { get { return _ComputerList; } }
我需要的标签结果是这样的
int workingItems= ComputerList.Where(x=> x.isWorking == true).Count()
然后绑定(bind)到标签
<Label Content="{Binding workingItems}" HorizontalAlignment="Left" Margin="12,424,0,0" VerticalAlignment="Top" Height="22" Width="62"/>
但是让这个工作的正确方法是什么?我不能在 WPF 本身中设置条件吗?
最佳答案
您可以创建仅获取属性
public int WorkingItems
{
get { return ComputerList.Where(x=> x.isWorking == true).Count(); }
}
现在,只要 ComputerList
或列表中存在任何 isWorking
属性,您就需要调用 INotifyPropertyChanged
的实现本身会改变。
以下是一些伪代码,可让您了解需要考虑什么才能通知任何可能的更新。 不建议也不完整完全像这样处理通知。
ComputerList.CollectionChanged += (s, e) => NotifyPropertyChanged("WorkingItems");
this.PropertyChanged += (s, e) => { if (e.PropertyName == "ComputerList") NotifyPropertyChanged("WorkingItems"); };
foreach (var item in ComputerList)
{
item.PropertyChanged += (s, e) => { if (e.PropertyName == "isWorking") NotifyPropertyChanged("WorkingItems"); };
}
关于c# - ObservableCollection 条件计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810621/