1

WPF 中有没有办法检查事件是否附加了方法?
我希望能够做类似的事情

if (MyEvent != Null)
{
...
}
4

1 回答 1

1

由于您正在创建自己的event,因此可以检查是否附加了方法。

下面我定义了一个方法IsMethodAttachedToMyEvent,它将检查给定Action的是否附加MyEvent。我已经使用了GetInvocationList()方法MyEvent来循环附加的方法。

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();
        }
    }
}
于 2013-01-30T07:20:36.787 回答