1

Is there a way in WPF to check if an event has a method attached to it?
I'd like to be able to do something like

if (MyEvent != Null)
{
...
}
Idov
  • 5,006
  • 17
  • 69
  • 106

1 Answers1

1

Since you are creating your own event, it is possible to check if a method is attached to it or not.

Below I have defined a method IsMethodAttachedToMyEvent which will check if the given Action is attached to MyEvent or not. I have used the GetInvocationList() method of MyEvent to loop through the attached methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public event Action MyEvent;

        public MainWindow()
        {

            InitializeComponent();

            MyEvent += new Action(MainWindow_MyEvent);

            MessageBox.Show("Is MainWindow_MyEvent attached\n\n" + IsMethodAttachedToMyEvent(new Action(MainWindow_MyEvent) ));
            MessageBox.Show("Is MainWindow_MyEvent_1 attached\n\n" + IsMethodAttachedToMyEvent(new Action(MainWindow_MyEvent_1)));
        }

        public bool IsMethodAttachedToMyEvent(Action methodToCheck)
        {
            if (MyEvent != null)
            {
                foreach (Action act in MyEvent.GetInvocationList())
                {
                    if (act.Method == methodToCheck.Method)
                    {
                        return true;
                    }
                }
            }
            return false;

        }

        void MainWindow_MyEvent()
        {
            throw new NotImplementedException();
        }

        void MainWindow_MyEvent_1()
        {
            throw new NotImplementedException();
        }
    }
}
Anand Murali
  • 4,091
  • 1
  • 33
  • 46