我必須在我的應用程序中實現「全局」搜索/過濾功能。每個包含信息列表的窗口(無論是DataGrid還是某個列表的其他實現)都必須有一個搜索框,並且如果用戶在搜索框中輸入文本,它將通過搜索任何內容來過濾該列表。我只想實現一次搜索邏輯。如何實現可用於不同類型對象的功能?
大多數情況下,這不一定會太困難。原因是大多數包含列表的窗口將基於相同的數據類型。這些都是ViewModels,每個ViewModel擴展ViewModelBase,ViewModelBase包含我將要搜索的數據。
一個基本的例子:
public class ZoneVm : ViewModelBase
{
// Zone specific functionality
}
public class UserVm : ViewModelBase
{
// User specific functionality
}
public class ViewModelBase : INotifyPropertyChanged
{
public string Name { get; set; }
public int Value { get; set; }
// The handy thing about the common view model base is that
// I can contain the model binding in a single place
// It will be easy to search List<ZoneVm> and List<UserVm> because
// they are both effectively List<ViewModelBase>.
}
的困難在於,我要尋找離羣對象。某些窗口包含不需要擴展ViewModelBase的對象列表,因此我不會有這個可預測的屬性列表進行搜索,例如,
public class PanelData // doesn't implement ViewModelBase :-(
{
public int SerialNumber { get; set; }
public Customer Customer { get; set; }
// other properties that I'll have to search/filter on
}
是否有這種任務的「最佳實踐」方法?有沒有解決這個問題的設計模式?我該如何處理搜索/過濾2個(可能更多)不同種類的列表?
你有沒有考慮過使用反射?您可以使用Attribute標記這些屬性,並在應用程序加載時解析它們,併爲這些搜索/可過濾屬性保存緩存的Accessors列表。 – dowhilefor 2012-07-19 08:55:54
Hi @dowhilefor(nice name,btw :-)),我沒有考慮反思,但現在認爲它可能是有用的。我可以迭代每個屬性(不管它是什麼),並將它的'ToString()'值與搜索項進行比較。隨着我進一步探索,我會記住這一點。謝謝。 – DaveDev 2012-07-19 11:01:33