Search code examples
c#wpfeventsprojects

How to subscribe to C# GUI event from ProjectA in dll in ProjectB


I have a C# WPF GUI in ProjectA. I raise an event in ProjectA and want to subscribe/respond to that event from within ProjectB which is a dll that knows nothing about ProjectA. ProjectA has references to objects in ProjectB, but not vice versa.

For example, user clicks a button in ProjectA. Inside ProjectA's button_Click() handler it calls UserClickedButtonX(this, e). ProjectB should subscribe to the UserClickedButtonEvent and handle it when the event is raised.

The code below doesn't work since ProjectB doesn't know about 'MainWindow' in ProjectA. Thanks in advance!

In ProjectA (Mainwindow.xaml.cs):
        private void buttonX_Click(object sender, RoutedEventArgs e) {
            OnUserClickedButtonXEvent(new EventArgs());
        }

        public static event UserClickedButtonXEventHandler UserClickedButtonXEvent;
        public virtual void OnUserClickedButtonXEvent(EventArgs e) {
            if (UserClickedButtonXEvent!= null)
                UserClickedButtonXEvent(this, e);
        }

In Project B (dll):
           MainWindow.UserClickedButtonXEvent+= new UserClickedButtonXEventHandler(UserClickedButtonXFunction);

        void UserClickedButtonXFunction(object source, EventArgs e) {
            Console.WriteLine("User clicked Button X on the GUI in another project!");
        }

Solution

  • You should be able to put this line into ProjectA (eg. MainWindow contructor):

    MainWindow.UserClickedButtonXEvent += ProjectB.ClassB.UserClickedButtonXFunction;
    

    Function has to be public static, or you have to create an instance of ClassB, eg. a singleton.