.net - Add delete button for every row in datagrid -
how add delete button every row in data grid (contains 2 fields) in wpf. while datagrid itemsource
observablecollection<result> and
public class result : inotifypropertychanged { public string friendlyname { get; set; } public string id { get; set; } public result(string name, string id) { this.friendlyname = name; this.id = id; } #region inotifypropertychanged members public event propertychangedeventhandler propertychanged; void onpropertychanged(string property) { if (this.propertychanged != null) { this.propertychanged(this, new propertychangedeventargs(property)); } } #endregion } }
you can add datagridtemplatecolumn , add button celltemplate. use built in applicationcommands.delete or own icommand button
<datagrid itemssource="{binding results}" autogeneratecolumns="false"> <datagrid.columns> <datagridtextcolumn header="friendlyname" binding="{binding friendlyname}"/> <datagridtextcolumn header="id" binding="{binding id}"/> <datagridtemplatecolumn header="delete"> <datagridtemplatecolumn.celltemplate> <datatemplate> <button content="delete" command="delete"/> </datatemplate> </datagridtemplatecolumn.celltemplate> </datagridtemplatecolumn> </datagrid.columns> </datagrid> update
if don't want use built in delete can use own icommand. here short example relaycommand can found in following link: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx. also, uploaded here: relaycommand.cs
<datagrid itemssource="{binding results}" selecteditem="{binding selectedresult}" autogeneratecolumns="false"> <datagrid.columns> <!-- ... --> <datagridtemplatecolumn header="delete"> <datagridtemplatecolumn.celltemplate> <datatemplate> <button content="delete" command="{binding relativesource={relativesource ancestortype={x:type datagrid}}, path=datacontext.deletecommand}" commandparameter="{binding}"/> </datatemplate> </datagridtemplatecolumn.celltemplate> </datagridtemplatecolumn> </datagrid.columns> </datagrid> and in viewmodel or code behind
private result m_selectedresult; public result selectedresult { { return m_selectedresult;} set { m_selectedresult = value; onpropertychanged("selectedresult"); } } private bool candelete { { return selectedresult != null; } } private icommand m_deletecommand; public icommand deletecommand { { if (m_deletecommand == null) { m_deletecommand = new relaycommand(param => delete((result)param), param => candelete); } return m_deletecommand; } } private void delete(result result) { results.remove(result); }
Comments
Post a Comment