c# - 从非 UI dll 显示对话框
问题描述
我正在构建一个 dll,它将用于 wpf 和其他类型的框架(windows 窗体、asp ...)。出于这个原因,我不想使用 Messagebox。哪个是将通知从 dll 发送到应用程序的最佳方式,并且每个人都决定向用户显示消息的方式(并等待用户的回答)?有人可以帮我找到正确的方法吗?
解决方案
您可以公开消费者可以订阅的事件。这是做这种事情的一般模式:
您可以创建自己的类来携带有关事件的数据:
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);
}
一般的想法是,您班级的消费者只需要知道发生了什么事情以及发生的事情的细节。如何使用、处理或显示该事件不是您的组件的责任。
推荐阅读
- algorithm - 此规范的线性算法?
- powerbi - Power BI 数据流更新,但数据集和报表不更新
- c++ - 如何解决“缺少vtable通常意味着第一个非内联虚成员函数没有定义。”
- google-chrome - SVG 无法在 Chrome 84 中的初始页面加载时呈现
- flutter - 颤振底部溢出像素与列
- python - 带有 bbox 的 Python wfs 请求导致请求 url 中出现不需要的字符
- recursion - 在不使用算术的情况下找到物体的深度
- angular - Typescript / Angular 8:使用 ngFor 更改显示的单个按钮颜色
- java - 扫描仪循环中断 + 正则表达式问题
- c# - 使用 opencvsharp 进行图像拼接