如何在Project中的dll中从ProjectS订阅C#GUI事件

时间:2014-12-21 10:21:18

标签: c# wpf events projects

我在ProjectA中有一个C#WPF GUI。我在ProjectA中引发了一个事件,并希望在ProjectB中订阅/响应该事件,这是一个对ProjectA一无所知的DLL。 ProjectA引用了ProjectB中的对象,但反之亦然。

例如,用户单击ProjectA中的按钮。在ProjectA的button_Click()处理程序中,它调用UserClickedButtonX(this,e)。 ProjectB应该订阅UserClickedButtonEvent并在引发事件时处理它。

以下代码不起作用,因为ProjectB不知道ProjectA中的“MainWindow”。提前谢谢!

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!");
        }

2 个答案:

答案 0 :(得分:0)

您应该能够将此行放入ProjectA(例如,MainWindow构造函数):

MainWindow.UserClickedButtonXEvent += ProjectB.ClassB.UserClickedButtonXFunction;

函数必须是公共静态的,或者你必须创建一个B类实例,例如。单身人士。

答案 1 :(得分:0)

考虑使用EventAggregator在发布\订阅事件方面将类彼此分离。

此模式利用发布者和订阅者可以在不了解彼此的情况下利用的消息(即字符串)。

[TestMethod]
public void eventaggregator()
{
    // Setup
    var subscription = "my_subscription";
    bool messageReceived = false;

    EventAggregator.Instance.Register(subscription, (parameter) =>
        {
            // Logic goes here...
            messageReceived = true;
        });

    // Test
    EventAggregator.Instance.Publish(subscription, "a parameter for subscibers");

    // Verify
    Assert.IsTrue(messageReceived);
}


public class EventAggregator
{
    #region Singleton
    static EventAggregator _eventAggregator = null;
    private EventAggregator() { }

    public static EventAggregator Instance
    {
        get
        {
            if (_eventAggregator == null)
            {
                _eventAggregator = new EventAggregator();
            }

            return _eventAggregator;
        }
    }
    #endregion

    List<Observer> _observers = new List<Observer>();

    public void Register(string subscription, Action<object> response)
    {
        var observer = new Observer() { Subscription = subscription, Respond = response };
        _observers.Add(observer);
    }

    public void Publish(string subscription, object payload)
    {
        foreach (var observer in _observers)
        {
            if (observer.Subscription == subscription)
            {
                observer.Respond(payload);
            }
        }
    }
}

public class Observer
{
    public string Subscription { get; set; }
    public Action<object> Respond {get; set; }
}