c# - WPF MVVM DataGrid filtering using ComboBox -
i have wpf mvvm application datagrid , combobox binded same list of entities in viewmodel class. want filter datagrid entries through combobox selection, proper way this? since i'm working mvvm, want achieve data bindings, , avoid useless code behind.
my xaml code following
<datagrid itemssource="{binding posts}" autogeneratecolumns="false" isreadonly="true"> <datagrid.columns> <datagridtextcolumn header="id" binding="{binding id}" /> <datagridtextcolumn header="title" binding="{binding title}" /> <datagridtextcolumn header="blogurl" binding="{binding blog.url}" /> </datagrid.columns> </datagrid> <combobox itemssource="{binding posts}" displaymemberpath="blog.url" /> viewmodel
public class mainwindowviewmodel { private sqlitedbcontext context; public list<post> posts { get; set; } public mainwindowviewmodel() { context = new sqlitedbcontext(); posts = context.posts.include(p => p.blog).tolist(); } } in addition, code combobox shows duplicates of urls, how can distinct these values?
thanks.
you bind combobox collection of unique urls create in view model.
you filter datagrid binding selecteditem property of combobox source property of view model filters posts source collection.
please refer following code sample.
view model:
public class mainwindowviewmodel : inotifypropertychanged { private readonly sqlitedbcontext context; private readonly list<post> _allposts; public mainwindowviewmodel() { context = new sqlitedbcontext(); _allposts = context.posts.include(p => p.blog).tolist(); _posts = _allposts; urls = _allposts.where(p => p.blog != null && !string.isnullorempty(p.blog.url)).select(p => p.blog.url).tolist(); } private list<post> _posts; public list<post> posts { { return _posts; } set { _posts = value; notifypropertychanged(); } } public list<string> urls { get; set; } private string _url; public string url { { return _url; } set { _url = value; notifypropertychanged(); posts = _allposts.where(p => p.blog != null && p.blog.url == _url).tolist(); } } public event propertychangedeventhandler propertychanged; private void notifypropertychanged([callermembername] string propertyname = "") { if (propertychanged != null) propertychanged(this, new propertychangedeventargs(propertyname)); } } view:
<datagrid itemssource="{binding posts}" autogeneratecolumns="false" isreadonly="true"> <datagrid.columns> <datagridtextcolumn header="id" binding="{binding id}" /> <datagridtextcolumn header="title" binding="{binding title}" /> <datagridtextcolumn header="blogurl" binding="{binding blog.url}" /> </datagrid.columns> </datagrid> <combobox itemssource="{binding urls}" selecteditem="{binding url}" />
Comments
Post a Comment