开发者

Button Trigger an Event Or Command that will be caught by another class

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 Ma开发者_StackOverflow社区inViewModel so I can call it.

I'm a little bit confused now.

EDIT The Buttons are created dynamically in PictoPanelViewModel


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:

  1. Add an event myButtonClickedEvn to PictoPanelViewModel
  2. Create a method TriggerMyButtonClickedEvn which simply triggers the event in PictoPanelViewModel
  3. Associate TriggerMyButtonClickedEvn to myButton.Click
  4. In MainViewModel, at the time your class sees PictoPanelViewModel, associate your method to the newly created event.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜