How to notify an item has selected from data grid in wpf and using mvvm? -
i trying notify item selected data grid because opening modal window while selecting item data grid. editing selected item in modal window , due not want raisedpropertychanged mechanism selected item because when try modify selected item, opens modal window. trying use event trigger fix issue getting errors. below related code:
viewmodel:
public observablecollection<student> sitems { { return ssitems; } set { ssitems = value; raisepropertychanged( "sitems" ); } } private studentsinformation studentinformation; public studentsinformation studentinformationobject { { return studentinformation; } set { studentinformation = value; raisepropertychanged( "studentinformationobject" ); } } public relaycommand<student> selectionchangedcommand { get; set; }
these lines of code in constructor:
selectionchangedcommand = new relaycommand<student>( item => { if( item != null ) { messengerinstance.send<student>( item, "selectedstudent" ); } } );
this collection bonded datagarid.
view:
<datagrid x:name="datagrid" grid.row="1" margin="5" isreadonly="false" columnheaderheight="30" itemssource="{binding path=sitems}" autogeneratecolumns="false" selecteditem="{binding path=selectedstudentobject, mode=twoway, updatesourcetrigger=propertychanged}"> <datagrid.columns> <!--<datagridcheckboxcolumn header="select" binding="{binding path=myselect, updatesourcetrigger=propertychanged}" isreadonly="false" />--> <datagridtextcolumn header="name" binding="{binding name}"></datagridtextcolumn> <datagridtextcolumn header="enrollment" binding="{binding enrollment}"></datagridtextcolumn> <datagridtextcolumn header="score" binding="{binding score}"></datagridtextcolumn> <datagridtextcolumn header="comment" binding="{binding comment}"></datagridtextcolumn> </datagrid.columns> <i:eventtrigger eventname="selectionchanged"> <cmd:eventtocommand command="{binding selectionchangedcommand}" commandparameter="{binding selecteditem}" /> </i:eventtrigger> </datagrid>
if remove trigger section datagrid populated desired data. if include trigger code error message:
items collection must empty before using itemssource.
i know there other ways fix kind of things. using mvvm light toolkit.
that event trigger should elsewhere. should placed in interaction.triggers
use this:
<datagrid...> <i:interaction.triggers> <i:eventtrigger eventname="selectionchanged"> <cmd:eventtocommand command="{binding selectionchangedcommand}" commandparameter="{binding selecteditem}" /> </i:eventtrigger> </i:interaction.triggers> </datagrid>
update
you should use
<cmd:eventtocommand x:name="selectionchanged" command="{binding selectionchangedcommand}" passeventargstocommand="true" />
and modify command in vm.
relaycommand<selectionchangedeventargs> selectionchangedcommand{get; private set;}