C#WinForm代表n个子表单 [英] c# winform delegates for n subforms
问题描述
我有一个C#主表单,可以在单独的选项卡中打开C#子表单.每个选项卡只是相同子表单的一个实例,因此选项卡代码如下:
I have a C# main form that opens up C# sub forms in separate tabs. Each tab is simply an instance of the same sub form so the tab code is like:
SubForm sf = new SubForm();
TabPage tp = new TabPage();
tp.Controls.Add(sf);
tabControl.TabPages.Add(tp);
可以有n个选项卡和子表单.然后,每个新的子窗体实例都有一个委托来处理外部事件更新,如下所示:
There can be n tabs and subforms. Then each new subform instance has a delegate to handle external event updates, like so:
public partial class SubForm : Form
{
... form setup ...
internal void DoStuff(value v)
{
if (InvokeRequired)
{
// Generic Action delegate
Invoke(new Action<string, string>(DoStuff), value);
return;
}
myLabel.Text = value;
Show();
}
}
单击订阅按钮,子表单中的特定键进行了Geode注册,并且该委托作为事件处理程序被传递:
Click the subscribe button and there's a Geode registration to specific keys in the subform, and the delegate is passed as an event handler:
private void button_Click(object sender, EventArgs e)
{
new Geode().RegisterMyListener(cache, key, DoStuff);
}
更新Geode键值后,便会处理更新.
When the Geode key value is updated then the update is handled.
这对于第一个子窗体工作正常.然后,使用第二或第三子窗体,每个子窗体的键的所有Geode订阅都将更新,但是所有更新仅由最近实例化的子窗体的委托处理.我没想到会发生这种情况,因为每个新的子窗体实例都没有带有新委托的自己的堆栈吗?
This is working fine for the 1st subform. Then with a 2nd or 3rd subform all the Geode subscriptions to each subform's keys are updating, but all the updates are being handled only by the most recently instantiated subform's delegate. I had not expected that to happen because doesn't each new subform instance have its own stack with a new delegate?
更新:将第二个密钥注册到Geode RegisterMyListener
后,如下所示:
UPDATE: Once a 2nd key is registered with Geode RegisterMyListener
like this:
region.GetSubscriptionService().RegisterKeys(s);
region.AttributesMutator.SetCacheListener(new Listener<string, string>(DoStuff));
然后,每个事件更新都引用最新的DoStuff
委托,而不引用以前的委托. Geode监听器是static
寄存器?我希望能够使用同一Listener
的许多实例来预订单独的密钥.那可能吗?还是我需要多个子窗体的多个侦听器?
then every event update references the latest DoStuff
delegate and never a previous one. So is a Geode listener a static
register? I am looking to be able to subscribe to separate keys with many instances of the same Listener
. Is that possible? Or am I going to need multiple listeners for multiple subforms?
推荐答案
您可以使用以下扩展方法来做到这一点:
You can do it with extension method like this:
public static class Extensions
{
public static void InvokeAction(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.Invoke(new MethodInvoker(() => { action(); }));
}
else
{
action();
}
}
}
用法:
public partial class SubForm : Form
{
public void SetExampleText(string text)
{
this.InvokeAction(() => { this.ExampleTextBox.Text = text; })
}
}
这篇关于C#WinForm代表n个子表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!