首页 > 解决方案 > 从非 UI dll 显示对话框

问题描述

我正在构建一个 dll,它将用于 wpf 和其他类型的框架(windows 窗体、asp ...)。出于这个原因,我不想使用 Messagebox。哪个是将通知从 dll 发送到应用程序的最佳方式,并且每个人都决定向用户显示消息的方式(并等待用户的回答)?有人可以帮我找到正确的方法吗?

标签: c#.netdialog

解决方案


您可以公开消费者可以订阅的事件。这是做这种事情的一般模式:

您可以创建自己的类来携带有关事件的数据:

public class NotificationEventArgs : EventArgs
{
    public NotificationEventArgs(string message)
    {
        Message = message;
    }
    public string Message { get; }
}

然后,您创建一个代表来表示事件的签名:

public delegate void OnNotificationEventHandler(SomeClass sender, NotificationEventArgs args);

然后,您的一个或多个类可以将此委托作为事件公开:

public class SomeClass
{
    private OnNotificationEventHandler _notificationEventHandler;
    public event OnNotificationEventHandler OnNotification
    {
        add { _notificationEventHandler += value; }
        remove { _notificationEventHandler -= value; }
    }

    protected void RaiseNotificationEvent(NotificationEventArgs args)
    {
        _notificationEventHandler?.Invoke(this, args);
    }

    public void SomeMethod()
    {
        //Your class does something that requires consumer notification
        var args = new NotificationEventArgs("Something happened!");
        //Raise the event for the consumers who are listening (if any)
        RaiseNotificationEvent(args);
    }

}

最后,您的消费类将订阅此事件:

SomeClass obj = new SomeClass();
obj.OnNotification += Obj_OnNotification;

private static void Obj_OnNotification(SomeClass sender, NotificationEventArgs args)
{
    //Handle the notification from the class here.
    Console.WriteLine(args.Message);
}

一般的想法是,您班级的消费者只需要知道发生了什么事情以及发生的事情的细节。如何使用、处理或显示该事件不是您的组件的责任。


推荐阅读