viewmodel中定義原始資料及篩選後的資料,篩選後的資料型別為ICollectionView
//原始資料列表
public ObservableCollection<SchoolOutDto> SchoolList { get; set; }
/// <summary>
/// 篩選資料後的列表
/// </summary>
public ICollectionView FilterSchoolList { get; set; }
//輸入框繫結的值
public string SchoolText
{
get => schoolText; set
{
schoolText = value;
//根據篩選的名稱重新整理列表
FilterSchoolList.Refresh();
}
}
在原始資料獲取到資料後繫結篩選後的資料
FilterSchoolList = CollectionViewSource.GetDefaultView(SchoolList);
FilterSchoolList.Filter = Filter; //此處的Filter為一個回撥函式
Filter
private bool Filter(object obj)
{
var m = obj as SchoolOutDto;
if (string.IsNullOrEmpty(SchoolText) )
{
return true;
}
//輸入框與選擇的列表一致時重置列表(此時為選擇了某條資料直接重置)
if (SelectedSchool != null && SelectedSchool.schoolName==SchoolText)
{
return true;
}
if (m.schoolName.Contains(SchoolText))
{
return true;
}
return false;
}