Reputation: 3262
I am trying to trigger an event from a Button that will be caught in a different class without having this class as an instance in my class. Can I do that?
Lets say my Buttons are getting created in PictoPanelViewModel and this class doesnt have any reference to the MainViewModel, I want myButton to trigger an event that will call a method inside MainViewModel.
I tried myButton.Command and myButton.Click but these two need a reference of MainViewModel so I can call it.
I'm a little bit confused now.
EDIT The Buttons are created dynamically in PictoPanelViewModel
Upvotes: 0
Views: 267
Reputation: 7468
SI assume that MainViewModel has a reference to PictoPanelViewModel at least for an instant, and, to be in the worst case, that the buttons have not been created yet at that time. If this is the case I would:
All this translates in code like this.
In PictoPanelViewModel:
this.myButton.Click += new System.EventHandler(this.TriggerMyButtonClickedEvn);
public event EventHandler myButtonClickedEvn;
private void TriggerMyButtonClickedEvn(object sender, EventArgs e)
{
if (myButtonClickedEvn != null)
myButtonClickedEvn(sender, e);
}
In MainViewModel (in a place where you have the instance of PictoPanelViewModel):
aPictoPanelViewModel.myButtonClickedEvn += new System.EventHandler (myButtonClickedInPictoPanelViewModel);
Upvotes: 1