简体   繁体   中英

How to register a event handler to the event of another class in constructor of MainPage.xaml.cs

Situation:

  • i have a MainViewModel class that contains a collection named
    “Problems” of type ItemViewModel class

  • i have a loadData function in MainviewModel class where
    ItemViewModel class is instantiated and instances are added to
    Problems collection .

  • i also have a public event Event1 that fires at the end of LoadData function.

Doubt :

I want to register the Event1 in constructor of MainPage.xaml.cs , so that it points to a eventhandler defined in MainPage.xaml.cs. How do it do it ?

Following is the code snippet from MainViewModel class , certain declarations have been skipped for sake of clarity

    public event EventDelegate Event1;
    public void LoadData()
    {
    //place RT  data here

        this.Problems.Add(new ItemViewModel() { ID = 0, ProblemName = "Fever"});
        this.Problems.Add(new ItemViewModel(){ID=1,ProblemName="Diarrhea"});
        this.Problems.Add(new ItemViewModel() { ID=2,ProblemName = "sprain" });
        this.Problems.Add(new ItemViewModel() { ID = 3, ProblemName = "bruise" });

        OnEvent1();
    }

   protected virtual void OnEvent1()
   {
       EventDelegate handler = Event1;
       if (handler!=null)
       {
           handler();
       }
   }

You must have set the DataContext of MainPage to MainViewModel , so get the instance and hook your event in constructor after InitializeComponent()

public MainPage()
{
   InitializeComponent();
   ......
   ((MainViewModel)DataContext).Event1 += HandlerName;
   ......
}

UPDATE

For comments:

We are wiring the event handler and event1 , shouldn't we write ((MainViewModel)DataContext).Event1 += new HandlerName.

No, you don't need to. Anyhow, you code won't work, have to use delegate name ie

((MainViewModel)DataContext).Event1 += new EventDelegate(HandlerName);

One stated earlier and one stated above are equivalent.

Second will the statement DataContext = App.ViewModel.MainViewModel; placed after InitializeComponent(); set the datacontext to MainViewModel.

Yeah it will, you can place it before or after InitializeComponent() and it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM