WPF – 无法更改OnChanged方法内的GUI属性(从FileSystemWatcher触发)

我想在OnChanged方法中更改GUI属性…(实际上我试图设置图像源..但为了简单起见,这里使用了一个按钮)。 每次filesystemwatcher检测到文件中的更改时都会调用它。它会到达“top”输出..但在尝试设置按钮宽度时会捕获exception。

但如果我把相同的代码放在一个按钮..它的工作正常。 我真诚地不明白为什么..能有人帮助我吗?

private void OnChanged(object source, FileSystemEventArgs e) { //prevents a double firing, known bug for filesystemwatcher try { _jsonWatcher.EnableRaisingEvents = false; FileInfo objFileInfo = new FileInfo(e.FullPath); if (!objFileInfo.Exists) return; // ignore the file open, wait for complete write //do stuff here Console.WriteLine("top"); Test_Button.Width = 500; Console.WriteLine("bottom"); } catch (Exception) { //do nothing } finally { _jsonWatcher.EnableRaisingEvents = true; } } 

我真的想做什么,而不是改变按钮宽度:

 BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get("blue ban 1"), "avatar"); 

问题是此事件是在后台线程上引发的。 您需要将回调封送回UI线程:

 // do stuff here Console.WriteLine("top"); this.Dispatcher.BeginInvoke(new Action( () => { // This runs on the UI thread BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get("blue ban 1"), "avatar"); Test_Button.Width = 500; })); Console.WriteLine("bottom"); 

我猜测FileSystemWatcher正在另一个线程上调用您的事件处理程序。 在事件处理程序中,使用应用程序的Dispatcher将其封送回UI线程:

 private void OnChanged(object source, FileSystemEventArgs e) { Application.Current.Dispatcher.BeginInvoke(new Action(() => DoSomethingOnUiThread())); } private void DoSomethingOnUiThread() { Test_Button.Width = 500; }