WPF-无法更改OnChanged方法内部的GUI属性(从FileSystemWatcher激发)

本文关键字:属性 GUI FileSystemWatcher 激发 内部 方法 OnChanged WPF- | 更新日期: 2024-09-19 17:48:11

我想更改OnChanged方法中的GUI属性。。。(事实上,我试图设置一个图像源……但为了简单起见,这里使用了一个按钮)。每当filesystemwatcher检测到文件中的更改时,就会调用此操作。。并到达"顶部"输出。。但是当它试图设置按钮宽度时捕捉到异常。

但是如果我把同样的代码放在一个按钮上。。它工作得很好。我真的不明白为什么。。有人能帮我吗?

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");

WPF-无法更改OnChanged方法内部的GUI属性(从FileSystemWatcher激发)

问题是此事件是在后台线程上引发的。您需要将调用封送回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;
}