Search code examples
c#wpfxamlxamarinevents

Call event outside from class without reference


I want to call a C# ContentDialog from another class like:

var myDialog = new MyDialog();
await myDialog .ShowAsync();

But I do not want to have a reference to this dialog in the class. Later I want to access the dialog to change the state of a process bar. My Ideas was to create an event inside of myDialog which is invoked by a method of the constructing class. Is this possible or are there other possibilities to get this done?

Thank you for your help!


Solution

  • You wont get away without any reference to your myDialog instance or a member of that instance (e.g. a reference to a method that handles an event). That is because there is no way to access something that you dont know anymore.

    One solution could be as follows (which is probably what you had in mind already):

    • Create a MyDialog instance myDialog.
    • Save a reference to a UpdateStatusBar() method of your myDialog instace. This could be done by adding the method to an event in your calling class:
    //event
    public event Action NewStatusAvaliable;
    
    //event handler assignment (without arguments)
    NewStatusAvaliable += myDialog.UpdateStatusBar;
    //or with arguments
    NewStatusAvaliable += () => myDialog.UpdateStatusBar();
    
    • Call myDialog.ShowAsync();