c# - Select multiple items from a DataGrid in an MVVM WPF project -
how can select multiple items datagrid
in mvvm wpf project?
you can add custom dependency property this:
public class customdatagrid : datagrid { public customdatagrid () { this.selectionchanged += customdatagrid_selectionchanged; } void customdatagrid_selectionchanged (object sender, selectionchangedeventargs e) { this.selecteditemslist = this.selecteditems; } #region selecteditemslist public ilist selecteditemslist { { return (ilist)getvalue (selecteditemslistproperty); } set { setvalue (selecteditemslistproperty, value); } } public static readonly dependencyproperty selecteditemslistproperty = dependencyproperty.register ("selecteditemslist", typeof (ilist), typeof (customdatagrid), new propertymetadata (null)); #endregion }
now can use datagrid
in xaml:
<window x:class="datagridtesting.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:local="clr-namespace:datagridtesting.customdatagrid" title="mainwindow" height="350" width="525"> <dockpanel> <local:customdatagrid itemssource="{binding model}" selectionmode="extended" alternatingrowbackground="aquamarine" selectionunit="fullrow" isreadonly="true" snapstodevicepixels="true" selecteditemslist="{binding testselected, mode=twoway, updatesourcetrigger=propertychanged}"/> </dockpanel> </window>
my viewmodel
:
public class myviewmodel : inotifypropertychanged { private static object _lock = new object (); private list<mymodel> _mymodel; public ienumerable<mymodel> model { { return _mymodel; } } private ilist _selectedmodels = new arraylist (); public ilist testselected { { return _selectedmodels; } set { _selectedmodels = value; raisepropertychanged ("testselected"); } } public myviewmodel () { _mymodel = new list<mymodel> (); bindingoperations.enablecollectionsynchronization (_mymodel, _lock); (int = 0; < 10; i++) { _mymodel.add (new mymodel { name = "test " + i, age = * 22 }); } raisepropertychanged ("model"); } public event propertychangedeventhandler propertychanged; public void raisepropertychanged (string propertyname) { var pc = propertychanged; if (pc != null) pc (this, new propertychangedeventargs (propertyname)); } }
my model:
public class mymodel { public string name { get; set; } public int age { get; set; } }
and finally, here code behind of mainwindow
:
public partial class mainwindow : window { public mainwindow () { initializecomponent (); this.datacontext = new myviewmodel (); } }
i hope clean mvvm design helps.
Comments
Post a Comment