【问题标题】:WPF - Cannot change a GUI property inside the OnChanged method (fired from FileSystemWatcher)WPF - 无法更改 OnChanged 方法中的 GUI 属性(从 FileSystemWatcher 触发)
【发布时间】:2013-12-13 20:19:20
【问题描述】:

我想更改 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");

【问题讨论】:

    标签: c# wpf filesystemwatcher


    【解决方案1】:

    问题是这个事件是在后台线程上引发的。您需要将调用编组回 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");
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        • 2013-02-22
        相关资源
        最近更新 更多