WPF - Listview with button -
i have listview template , 1 column button. need selected item when click in button. how can ??
to cature selected listview item inside button pressed event can leverage mvvm pattern. in listview, in xaml, bind itemssource , selecteditem viewmodel class. bind button command in template runcommand in viewmodel.
the tricky part getting binding correct template active datacontext.
once can capture selectedcustomer inside runcommand gets executed when button gets pressed.
i've included of code started. can find implementations of viewmodelbase , delegatecommand via google.
here xaml:
<window x:class="listviewscrollposition.views.mainview" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="main window" height="400" width="400"> <grid> <listview itemssource="{binding path=customers}" selecteditem="{binding path=selectedcustomer}" width="auto"> <listview.view> <gridview> <gridviewcolumn header="first name"> <gridviewcolumn.celltemplate> <datatemplate> <stackpanel margin="6,2,6,2"> <textblock text="{binding firstname}"/> </stackpanel> </datatemplate> </gridviewcolumn.celltemplate> </gridviewcolumn> <gridviewcolumn header="last name"> <gridviewcolumn.celltemplate> <datatemplate> <stackpanel margin="6,2,6,2"> <textblock text="{binding lastname}"/> </stackpanel> </datatemplate> </gridviewcolumn.celltemplate> </gridviewcolumn> <gridviewcolumn header="address"> <gridviewcolumn.celltemplate> <datatemplate> <stackpanel margin="6,2,6,2"> <button content="address" command="{binding path=datacontext.runcommand, relativesource= {relativesource findancestor, ancestortype={x:type itemscontrol}}}"/> </stackpanel> </datatemplate> </gridviewcolumn.celltemplate> </gridviewcolumn> </gridview> </listview.view> </listview> </grid> </window>
here viewmodel:
using system.collections.objectmodel; using system.windows.input; using listviewscrollposition.commands; using listviewscrollposition.models; namespace listviewscrollposition.viewmodels { public class mainviewmodel : viewmodelbase { public icommand runcommand { get; private set; } public mainviewmodel() { runcommand = new delegatecommand<object>(onruncommand, canruncommand); _customers = customer.getsamplecustomerlist(); _selectedcustomer = _customers[0]; } private observablecollection<customer> _customers = new observablecollection<customer>(); public observablecollection<customer> customers { { return _customers; } } private customer _selectedcustomer; public customer selectedcustomer { { return _selectedcustomer; } set { _selectedcustomer = value; onpropertychanged("selectedcustomer"); } } private void onruncommand(object obj) { // use selectedcustomer object here... } private bool canruncommand(object obj) { return true; } } }
here link in viewmodel view:
public partial class mainview : window { public mainview() { initializecomponent(); datacontext = new viewmodels.mainviewmodel(); } }
Comments
Post a Comment