将委托添加到 Windows 窗体 [英] Add delegate to Windows Form
问题描述
问题:我想将相同的消息写入我正在写入日志文件的文本框控件.
Problem: I want to write the same message to a textbox control that I am writing to a log file.
我有一个 windows 窗体 (Form1.cs),它调用静态方法的横切类.在每个横切方法中,他们调用 WriteLogEntry 来更新他们正在做的事情的日志文件.我想将一个事件发送回 Form1,以便我可以将相同的日志消息写入表单上的控件.
I have a windows form (Form1.cs) that calls a crosscutting class of static methods. In each of the crosscutting methods, they call WriteLogEntry to update a log file of what they are doing. I'd like to send back an event to Form1 so I can write the same log message to a control on the form.
我查看了事件,但对理解示例的理解不够,也没有找到足够简单的示例来执行我想要的操作.有人可以向我展示如何向我的代码添加事件以完成此操作的简单示例吗?
I have looked at events but do not understand enough to make sense of the examples and have not found a simple enough example to do what I want. Can someone show me a simiple example of how to add an event to my code to accomplish this?
namespace MainForm
{
public delegate void MyDel(string str);
public partial class Form1 : Form
{
public event MyDel MyEvent;
public Form1()
{
InitializeComponent();
MyEvent += new MyDel(WriteSomething);
Crosscutting.DoSomething();
}
public void WriteSomething(string message)
{
Console.WriteLine(message);
}
}
//Crosscutting.cs
public class Crosscutting
{
private static void WriteLogEntry(string message)
{
// Code to write message to log file.
}
public static void DoSomething()
{
WriteSomething obj = new WriteSomething();
// Code to do something.
WriteLogEntry("I'm doing something");
}
}
}
推荐答案
在无法弄清楚如何使用委托返回表单后,我尝试了另一种方法.通过在MyClass"上创建 Form1 的实例,我能够使用公共方法写回表单.不是我想要的方式,但这是目前完成它的一种方式.如果有人能解释如何以更好的方式做到这一点,请这样做.
After not being able to figure out how to use a delegate to get back to the form, I tried another way. By creating an instance of Form1 on "MyClass", I was able to use a public method to write back to the form. Not the way I wanted, but it is a way to get it done for now. If anyone can explain how to do this a better way, please do so.
public partial class Form1 : Form
{
private string message = string.Empty;
public static Form1 form;
public Form1()
{
InitializeComponent();
form = this;
}
public void UpdateTextBox(string message)
{
textBox1.Text += message + Environment.NewLine;
this.Update();
}
private void button1_Click(object sender, EventArgs e)
{
var myClass = new MyClass();
myClass.DoSomething();
}
}
public class MyClass
{
public void DoSomething()
{
Log("I did something");
}
private void Log(string message)
{
Console.WriteLine(message);
Form1.form.UpdateTextBox(message);
}
}
这篇关于将委托添加到 Windows 窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!