作者:转身-说离别2013 | 来源:互联网 | 2023-09-09 19:42
在WPF中,我有一个绑定到字典(ListView
)的InpLangList
和一个具有boolean(CheckBox
)属性的IsShowEmptyFields
。
例如。 private Dictionary _langList = new Dictionary();
public Dictionary InpLangList
{
get { return _langList ; }
set
{
_langList = value;
NotifyPropertyChanged();
}
}
(...)
InpLangList.Add("id1","One");
InpLangList.Add("id2","");
InpLangList.Add("id3","");
InpLangList.Add("id4","Four");
InpLangList.Add("id5","Five");
(...)
private bool _isShowEmptyFields;
public bool IsShowEmptyFields
{
get { return _isShowEmptyFields; }
set
{
_isShowEmptyFields = value;
NotifyPropertyChanged();
}
}
我需要的是,如果选中了复选框,那么我只想显示空白字段,
即
InpLangList.Add("id2","");
应显示在ListView中
否则,整个InpLangList
应该显示在ListView中。
使用CollectionView:
ViewModel:
await
查看:
// Actual data source
Dictionary inpLangList = new Dictionary();
// A presentation of your data that you can group,sort,filter,etc
public ICollectionView InpLangList { get; set; }
private bool _isShowEmptyFields;
public bool IsShowEmptyFields
{
get { return _isShowEmptyFields; }
set
{
_isShowEmptyFields = value;
// if the presentation of your data is assigned - filter it
InpLangList?.Refresh();
}
}
// ViewModel constructor
public VM()
{
inpLangList.Add("id1","One");
inpLangList.Add("id2","");
inpLangList.Add("id3","");
inpLangList.Add("id4","Four");
inpLangList.Add("id5","Five");
// note what's going next:
// assigning the data source to it's presentation (view)
InpLangList = CollectionViewSource.GetDefaultView(inpLangList);
// assigning filter that will be applied to your data source
// before the showing it within the UI
InpLangList.Filter = (obj) =>
{
if (!(obj is KeyValuePair pair))
return false;
return !IsShowEmptyFields || string.IsNullOrEmpty(pair.Value);
};
}