gul*_*aek 2 c# wpf binding inotifypropertychanged
我知道如何绑定到Count,但是如果我只想要类型为Product的计数,我该怎么做呢
<TextBlock Text="{Binding Items.Count}" />
Items = new ObservableCollection<object>();
Run Code Online (Sandbox Code Playgroud)
我尝试使用属性,但是在添加或删除项目时,我遇到了保持同步的问题.
public int ProductCount
{
get
{
return Items.Cast<object>().Count(item => item.GetType() == typeof (ProductViewModel));
}
}
Run Code Online (Sandbox Code Playgroud)
使用LINQ OfType()可以在ProductCount属性getter中返回以下语句的值:
return Items.OfType<ProductViewModel>().Count();
Run Code Online (Sandbox Code Playgroud)
顺便说一下,在无效检查条件下更安全地使用:
return Items == null ? 0 : Items.OfType<ProductViewModel>().Count();
Run Code Online (Sandbox Code Playgroud)
BTW2,避免在这种情况下使用Cast <>,因为它会在无效的强制转换操作时抛出InvalidCastException异常.