c# - How to add item in DataGrid (smart way) -
actually read lot of solution long. there no way make this:
datagrid.items.add("element");
?
since you're using wpf, you'll want create list use datagrid.itemssource = yourclasstoshowlist;
. auto populate columns , row items you. upon event selecteditemchanged
can grab single (or multiple) selected youclasstoshow
's. wpf make simple bind data ui controls.
here examples:
xaml
<datagrid x:name="dg" margin="10,32,10,111" alternatingrowbackground="white" selectionchanged="dgdailymediareport_selectionchanged" isreadonly="true" autogeneratecolumns="false" selectionmode="single" > <datagrid.columns> <datagridtemplatecolumn header="{binding status}" width="75"> <datagridtemplatecolumn.celltemplate> <datatemplate> <grid> <progressbar height="20" grid.row="0" grid.column="0" minimum="0" maximum="500" value="{binding totalprogress, mode=oneway}"></progressbar> <label horizontalalignment="center" content="{binding totalpercent,mode=oneway}"></label> </grid> </datatemplate> </datagridtemplatecolumn.celltemplate> </datagridtemplatecolumn> <datagridtextcolumn header="name" binding="{binding name}" foreground="darkred" /> <datagridtextcolumn header="age" binding="{binding age}" /> </datagrid.columns> <datagrid.contextmenu> <contextmenu> <menuitem x:name="menushowinfolder" header="show in folder" click="menushowinfolder_click"/> </contextmenu> </datagrid.contextmenu> </datagrid>
c#
window_loaded event:
list<yourclass> yourclasslist = yourclasslistrepo.getyourclasses(); dg.itemssource = yourclasslist;
dg_selectionchanged event:
if(dg.selecteditems.count > 0){ foreach(yourclass yourclass in (list<yourclass> dg.selecteditems)){ messagebox.show(yourclass.name); } }
binding="{binding name}"
"name" in context objects public property.
so you'll need public access method public string name {get;set}
side note: change object's property value , have auto show, you'll need inotifypropertychanged
on object itself:
person class:
public class person: inotifypropertychanged { #region property_changed_events public event propertychangedeventhandler propertychanged; protected virtual void onpropertychanged(string propertyname) { propertychangedeventhandler handler = propertychanged; if (handler != null) handler(this, new propertychangedeventargs(propertyname)); } protected bool setfield<t>(ref t field, t value, string propertyname) { if (equalitycomparer<t>.default.equals(field, value)) return false; field = value; onpropertychanged(propertyname); return true; } #endregion private string _name; public string name { { return _name; } set { setfield(ref _name, value, "name"); } } }
Comments
Post a Comment