WPF - Cannot change a GUI property inside the OnChanged method (fired from FileSystemWatcher)

后端 未结 2 690
眼角桃花
眼角桃花 2020-12-21 02:14

I want to change a GUI property in the OnChanged method... (in actuality im trying to set an image source.. but used a button here for simplicity). This is called everytime

相关标签:
2条回答
  • 2020-12-21 02:28

    I'm guessing that the FileSystemWatcher is calling your event handler on another thread. Inside your event handler, use your application's Dispatcher to marshal it back to the UI thread:

    private void OnChanged(object source, FileSystemEventArgs e) {
        Application.Current.Dispatcher.BeginInvoke(new Action(() => DoSomethingOnUiThread()));
    }
    
    private void DoSomethingOnUiThread() {
        Test_Button.Width = 500;
    }
    
    0 讨论(0)
  • 2020-12-21 02:42

    The problem is that this event is raised on a background thread. You need to marshal the call back to the UI thread:

    // 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");
    
    0 讨论(0)
提交回复
热议问题