我有一个带有事件处理程序的主窗口,它不能正常工作。我已经制作了这个问题的简单模型。请在问题所在的代码中查看注释:
public partial class MainWindow : Window
{
public event EventHandler Event1;
public MainWindow()
{
Event1 += MainWindow_Event1;
InitializeComponent();
}
void MainWindow_Event1(object sender, EventArgs e)
{
textBox1.Text = "wth!?"; //Not changing text box. Not showing message. If delete this line, it will work fine
MessageBox.Show("raised");
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
EventHandler evt = Event1;
while (true)
{
Thread.Sleep(500);
evt(null, null);
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerAsync();
}
}
请解释此行为,我该如何解决?
最佳答案
问题是您从后台线程调用事件。这将不起作用,并且程序在尝试访问 TextBox
时只是挂起。但是,如果您更改此代码:
textBox1.Text = "wth!?"; //Not changing text box. Not showing message. If delete this line, it will work fine
MessageBox.Show("raised");
为此:
this.Dispatcher.BeginInvoke((Action)delegate()
{
textBox1.Text = "wth!?"; //Not changing text box. Not showing message. If delete this line, it will work fine
MessageBox.Show("raised");
});
它会为你工作。
关于c# - 事件未在表单中正确引发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15210016/