クラスがイベントを使用して親フォームのコントロールにコールバックする方法の例を探しています。この場合、イベントは親ではなくクラスで発生します。たとえば、クラスがあり、フォームのテキストボックスを更新する必要があるクラスで何かが発生した場合。
フォームのテキストボックスをプロパティとして公開し、フォームのインスタンスをクラスに渡すことでこれを行いましたが、テキストボックスを更新するだけでも大変な作業のようです。
私はC#を独学しようとしているので、初心者です。ケン
public class Form1 : Form
{
EventClass eventClassInstance;
public Form()
{
eventClassInstance = new EventClass();
eventClassInstance.actualEvent += new EventClass.CustomEventHandler(eventHandler);
}
private void eventHandler(object sender)
{
//Do something
}
}
public class EventClass
{
public delegate void CustomEventHandler(object sender);
public CustomEventHandler actualEvent;// This gets fired somewhere
public EventClass()
{
}
}
これは、親クラスのイベント ハンドラーの簡単な例です。
イベントの公開に関するこのMSDN の記事をご覧になることをお勧めします。渡したい情報によっては、カスタム EventArgs を作成して情報を渡し、デリゲートとイベントを作成する必要がある場合があります。
これは、上記の MSDN リンクを大幅に借用した簡単で汚い例です。簡単なテストのためにタイマーが追加されました。
フォーム1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Class1 myClass = new Class1();
myClass.RaiseCustomEvent += new EventHandler<CustomEventArgs>(myClass_RaiseCustomEvent);
}
void myClass_RaiseCustomEvent(object sender, CustomEventArgs e)
{
this.Text = e.Message;
}
}
クラス1
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Class1
{
public event EventHandler<CustomEventArgs> RaiseCustomEvent;
public Class1()
{
Timer tmr = new Timer();
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Interval = 2000;
tmr.Start();
}
void tmr_Tick(object sender, EventArgs e)
{
CustomEventArgs ea = new CustomEventArgs("Hello World");
RaiseCustomEvent(this, ea);
}
}
public class CustomEventArgs : EventArgs
{
public CustomEventArgs(string s)
{
msg = s;
}
private string msg;
public string Message
{
get { return msg; }
}
}
}
クラスが更新アクションをトリガーする方法がわからない。そこで、ユーザーがボタンをクリックしてクラスを呼び出して何かを実行する単純なケースを考えてみましょう。次のように、フォームからクラスにコールバックを渡すことができます。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Class1 class1 = new Class1();
class1.DoSomething(OnSuccess, OnError);
}
private void OnSuccess(string newValue)
{
textBox1.Text = newValue;
}
private void OnError(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
クラスはタスクを終了し、コールバックに更新された値を渡しますが、呼び出し元が更新された値をどのように処理するかはわかりません。
public class Class1
{
public void DoSomething(Action<string> onSuccess, Action<Exception> onError)
{
try
{
// Logic to really do something...
if (onSuccess != null)
onSuccess("updated value");
}
catch (Exception ex)
{
if (onError != null)
onError(ex);
}
}
}
ラムダ式を学習した場合は、呼び出しをその場でクラスに戻すことができます。
private void button1_Click(object sender, EventArgs e)
{
Class1 class1 = new Class1();
class1.DoSomething(
newValue => textBox1.Text = newValue,
ex => MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error));
}
このプロセスに従うようにしてください。