c# - Binding selected items to list<t> in viewmodel -


i have following property in view model:

public list<departments> departmentlist {     { return newtechnician.departmentlist; }     set     {         newtechnician.departmentlist = value;         onpropertychanged("departmentlist");     } } 

i have datagrid bound list, following values

public class departments {     public int departmentid { get; set; }     public string departmentdescription { get; set; }     public int requestaccess { get; set; }     public int queueaccess { get; set; }     public int departmentstatus { get; set; }     public bool selected { get; set; } } 

i need able insert departmentid selected rows database. how can bind values departmentid based on selected rows in either existing list or new list. (the selection mode set extended)

foreach (departments department in createnewtech.selecteddepartments) {     if (department.selected == true)     {         sql = @"insert tech_department_link values(@techid,@departmentid)";          using (sqlcommand command = new sqlcommand(sql, con))         {             command.parameters.addwithvalue("@techid", createnewtech.newtech.techid);             command.parameters.addwithvalue("@departmentid", department.departmentid);              command.executenonquery();         }     } } 

first of all, should better not insert modelitems in plain datagrid. better should create observablecollection generic type of departmentviewmodel, holds department , properties "isselected", isn't model property helper property logic , view.

then can go xaml datagrid is, , following:

<datagrid itemssource="{binding departmentviewmodels}">     <datagrid.itemcontainerstyle>         <style targettype="datagridrow">             <setter property="isselected" value="{binding isselected, mode=twoway}" />         </style>     </datagrid.itemcontainerstyle> </datagrid> 

your viewmodel departments holds property this:

public observablecollection<departmentviewmodel> departmentviewmodels 

then can ids of selected departments via

var ids = (from dpvm in this.departmentviewmodels             dpvm.isselected             select dpvm.id).tolist(); 

edit: if want stay model directly in list, first snipped must following:

<datagrid itemssource="{binding departmentlist}">     <datagrid.itemcontainerstyle>         <style targettype="datagridrow">             <setter property="isselected" value="{binding selected, mode=twoway}" />         </style>     </datagrid.itemcontainerstyle> </datagrid> 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -