c# - Updating datagrid WPF -
i have created window:
when add new user, delete or update, applies server. doesn't update datagrid below. here 1 of functions :
private void delete_button_click(object sender, routedeventargs e) { using(var ctx = new personelcontext()) { personelentity personel = ( s in ctx.personels s.name == namebox.text select s).firstordefault(); ctx.personels.remove(personel); ctx.savechanges(); } this.personelentitydatagrid.items.refresh(); }
as see i'm refreshing datagrid still doesn't show new results. how can fix this?
mvvm exemple
let's have got windows datagrid :
<window x:class="wpfapplication7.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="mainwindow" height="350" width="525"> <datagrid itemssource="{binding personels}"> <datagrid.columns> <datagridtextcolumn header="nom" binding="{binding nom}" width="200"></datagridtextcolumn> </datagrid.columns> </datagrid> </window>
we have define datacontext (or binding won't know find) :
namespace wpfapplication7 { public partial class mainwindow : window { public mainwindow() { initializecomponent(); this.datacontext = new mainviewmodel(this); } } }
then can define viewmodel (datacontext of windows) :
class mainviewmodel : viewmodelbase { /// <summary> /// référence de la fenêtre principale /// </summary> private mainwindow mainwindow; /// <summary> /// liste des personels /// </summary> private observablecollection<personel> personels = new observablecollection<personel>(); public observablecollection<personel> personels { { return personels; } } /// <summary> /// constructeur de la classe /// </summary> /// <param name="mainwindow">référence de la fenêtre principale</param> public mainviewmodel(mainwindow mainwindow) { this.mainwindow = mainwindow; addpersonel("toto"); addpersonel("jack"); addpersonel("momo"); addpersonel("momo"); addpersonel("momo"); addpersonel("momo"); } private void addpersonel(string namepersonel) { personels.add(new personel() { name = namepersonel }); onpropertychanged("personels"); } } class personel { private string name = "noname"; public string name { { return name; } set { name = value; } } }
mainviewmodel must implement inotifypropertychanged notifies controls property value has changed. :
public abstract class viewmodelbase : inotifypropertychanged { public event propertychangedeventhandler propertychanged; protected virtual void onpropertychanged(string propertyname) { if (this.propertychanged != null) { this.propertychanged(this, new propertychangedeventargs(propertyname)); } } }
Comments
Post a Comment