Spa*_*pan 0 c# events scope event-handling winforms
我是事件编程的新手,我显然误解了我正在尝试做的事情.
我有一个Windows窗体应用程序订阅来自另一个类的事件.Ť
//Class that provides event handler to Windows Forms application.
class Foo
{
public string Value{get; set;}
// Lots of other code
public void OnEventFired(object sender, EventArgs e)
{
// Attempt to access variable Value here.
}
}
Run Code Online (Sandbox Code Playgroud)
从Windows窗体代码我首先Value在类中设置变量,Foo然后触发将执行OnEventFired上面代码的事件.
我所看到的是,当在事件处理程序中使用时,变量Value不包含在事件被触发之前设置的值(Value为空).
我知道我可以扩展EventArgs到包含变量数据,但我试图理解为什么我正在做的事情不起作用.
这是一个有效的简短示例.将此与您的代码进行比较,以找出问题所在.
using System;
using System.Windows.Forms;
class Foo
{
public string Value { get; set; }
public void HandleClick(object sender, EventArgs e)
{
((Control)sender).Text = Value;
}
}
class Program
{
public static void Main()
{
Foo foo = new Foo { Value = "Done" };
Button button = new Button { Text = "Click me!" };
button.Click += foo.HandleClick;
Form form = new Form
{
Controls = { button }
};
Application.Run(form);
}
}
Run Code Online (Sandbox Code Playgroud)
我的猜测是你使用了与Foo你设置的实例不同的实例来连接事件处理程序Value.例如,像这样:
Foo foo = new Foo { Value = "Done" };
...
// Different instance of Foo!
button.Click += new Foo().HandleClick;
Run Code Online (Sandbox Code Playgroud)
......但是如果没有看到更多的代码,很难分辨.
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |