c# - Whats best practice to access Model inside Command in MVVM pattern in UWP app -
lets have simple ui in mainpage.xaml
<listview itemsources="{binding records}" itemtemplate="{staticresource recordtemplate}"> </listview>
in app.xaml
<datatemplate x:key="recordtemplate"> <textblock text="{binding title}"/> <button content="change title" command="{binding datacontext.changetitlecommand, relativesource={relativesource ancestortype=listview}}"/> </datatemplate>
i want keep record
class simple , clean possible, have 1 property title
.
in mainviewmodel.cs
, in changetitlecommand
want access record model of listviewitem click on button.
i can cast sender
object frameworkelement
, access datacontext
, cast record
type , start making change. ugly , require viewmodel aware of view (frameworkelement), make viewmodel not reuseable in difference ui framework, want avoid approach.
one possibility bind command in record class, not in mainviewmodel (remove relativesource={relativesource ancestortype=listview}}
part). way access model this
keyword. way make record
class become mess add more functions , event-to-command recordtemplate
.
so best practice access model inside command ?
you can put template resources of mainpage.xaml
, set command
property following:
{binding changetitlecommand, source={staticresource viewmodelname}}.
or can set name page , write following:
{binding datacontext.changetitlecommand, elementname='pagename'}
Comments
Post a Comment