我有三个类,一个类在配置文件中加载到内存中以便稍后访问。我的另一类是主要形式。我试图实现的是,当加载配置类的某些元素时,它们被添加到GUI(WindowsForm)中的列表视图中。
我知道你不能直接从其他非mainform类访问GUI,这在看完之后我不想再做了,所以我一直试图激活事件说“config updated”表示mainform将在适当时监听并更新列表视图。所以我创建了一个定义事件和委托等的第三个类,但在我看到的所有示例中,如果不同的类调用事件,它们都会传递给事件类的共享实例。
这是我应该做的事情吗?当我从mainform类创建配置类时,我应该传递一个事件类的实例吗?或者,对于彼此不了解的两个班级是否有办法分享活动?
我已经修改了下面的微软示例,以半示范我需要的内容。
using System;
public class FireEventArgs : EventArgs
{
public FireEventArgs(string room, int ferocity)
{
this.room = room;
this.ferocity = ferocity;
}
public string room;
public int ferocity;
}
public class FireAlarm
{
public delegate void FireEventHandler(object sender, FireEventArgs fe);
public event FireEventHandler FireEvent;
public void ActivateFireAlarm(string room, int ferocity)
{
FireEventArgs fireArgs = new FireEventArgs(room, ferocity);
if(FireEvent!=null)FireEvent(this, fireArgs);
}
}
public class FireEventTest
{
public static void ExtinguishFire(object sender, FireEventArgs fe)
{
Console.WriteLine("\nThe ExtinguishFire function was called by {0}.", sender.ToString());
if (fe.ferocity < 2)
Console.WriteLine("This fire in the {0} is no problem. I'm going to pour some water on it.", fe.room);
else if (fe.ferocity < 5)
Console.WriteLine("I'm using FireExtinguisher to put out the fire in the {0}.", fe.room);
else
Console.WriteLine("The fire in the {0} is out of control. I'm calling the fire department!", fe.room);
}
public static void Main()
{
FireAlarm myFireAlarm = new FireAlarm();
FireAlarm fireAlarm = new FireAlarm();
fireAlarm.FireEvent += new FireAlarm.FireEventHandler(ExtinguishFire);
myFireAlarm.ActivateFireAlarm("Kitchen", 3);
myFireAlarm.ActivateFireAlarm("Study", 1);
myFireAlarm.ActivateFireAlarm("Porch", 5);
return;
}
}
提前感谢您的帮助。
答案 0 :(得分:1)
好吧,我不认为我完全理解你,但你可以有一个名为EventDispatcher的类,如果你愿意,可以把它变成Singleton,里面有一个公共事件
ConfigurationElementLoaded(object sender, ConfigurationElementLoadedArgs args)
以及触发事件的公共方法:
void FireConfigurationElementLoaded(ConfigurationElement element)
你可以在其中开火。
您的mainForm可以通过Singleton isntance订阅:EventDispatcher.Instance.ConfigurationElementLoaded += ...
,您的配置可以使用FireConfigurationElementLoaded
启动活动。
如果这个答案没有帮助,请详细说明你想要做什么......
答案 1 :(得分:0)
这绝对是绝对的,ui可以绝对地知道它应该显示什么,至少通过界面。你不想要的是让业务类依赖于UI(你想要一个单向的依赖流)
我会说要么定义一个包含你的事件的界面,要在FireAlarm
中实现它,要么直接听FireAlarm
中的事件。
另外,严格来说,不是表格外的代码不能在表格内使用的情况。对于ui来说,它的absolutley很好听,并使用你编写的自定义EventArgs事件,包括sender
对象。
真正重要的是运行相关代码的线程。只要从UI线程(创建ui的线程)访问UI,您就可以运行任何代码。
您发布的代码是否有效?
答案 2 :(得分:0)
如果您只想更新Windows窗体的UI上的内容,请在控件上使用数据绑定。
创建一个数据层,其中包含配置文件的信息并将其属性绑定到您的界面控件。目前,您更改该属性的值,数据绑定机制将关心更新您的UI。
在genareal中,我的观点是:如果您使用的框架中已存在某些内容 (在这种情况下,.NET框架)适合您的需求,只需使用它,不要发明脚本,导致其他人已经发明了它:)
DataBinding for WindowsForm example
看看所有这些事件,我认为我们正在谈论WindowsForm应用程序。如果没有,请准确。
希望这有帮助。