c# - How to call functions in a main view model from other view models? -
my program composed of treeview , 2 contentpresenters @ ground level. mainwindow, treeview, , each contentpresenter have own viewmodels.
i call function in mainwindowviewmodel treeviewviewmodel.
i need because mainwindowviewmodel controls displayed in contentpresenters, , manually update display.
i'm guessing this...
treeviewviewmodel:
public class treeviewviewmodel { //do need declare mainwindowvm? public treeviewviewmodel() { ... } private void function() { //command affects display //manually call function in mainwindowvm refresh view } } i have tried access mainwindowvm treeviewviewmodel using:
public mainwindowviewmodel viewmodel { { return datacontext mainwindowviewmodel; } } but doesn't make sense. because mwvm not datacontext of treeviewviewmodel.
the
delegatemethod used in , linked answer can used in parent-child relationship , in either direction. includes child view model parent view model,windowcode behind code behind of childwindow, or pure data relationships without ui involved. can find out more usingdelegateobjects delegates (c# programming guide) page on msdn.
i answered similar question earlier today. if take @ passing parameters between viewmodels post, you'll see answer involves using delegate objects. can replace these delegates (from answer) method(s) , work in same way.
please let me know if have questions.
update >>>
yes, sorry forgot wanted call methods instead... i've been working on many posts tonight. still using example other post, call method in parameterviewmodel_onparameterchange handler:
public void parameterviewmodel_onparameterchange(string parameter) { // call method here } think of delegate being path parent view model... it's raising event called readyforyoutocallmethodnow. in fact, don't need have input parameter. define delegate this:
public delegate void readyforupdate(); public readyforupdate onreadyforupdate { get; set; } then in parent view model (after attaching handler in other example):
public void childviewmodel_onreadyforupdate() { // call method here updatedisplay(); } as have multiple child view models, define delegate in class both have access to. let me know if have more questions.
update 2 >>>
after reading last comment again, i've thought of simpler method might achieve want... @ least, if understand correctly. possible bind directly child views parent view model. instance, allow bind button.command property in child view icommand property in parent view model:
in treeviewview:
<button content="click me" command="{binding datacontext.parentcommand, relativesource={relativesource ancestortype={x:type mainwindow}}}" /> this of course assumes instance of parent view model in question set datacontext of mainwindow.
Comments
Post a Comment