绑定时不支持异常

时间:2013-11-23 16:19:33

标签: c# wpf

如果创建了文件,我正试图从FileSystemWatcher(Name,FullPath)绑定2个字符串。

我正在使用ObservableCollection,也许我使用错了。

这就是我试过的

private void StartFileMonitor()
    {
        var _monitorFolders = new List<string> {
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).Replace("Roaming", string.Empty),
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
        };

        try {

            foreach (var folder in _monitorFolders) {

                // Check if Folder Exists
                if (Directory.Exists(folder)) {

                    FileSystemWatcher _fileSysWatcher = new FileSystemWatcher();

                    _fileSysWatcher.Path = folder;
                    _fileSysWatcher.Filter = "*.*";

                    // Created
                    _fileSysWatcher.Created += (sender, e) => {

                        _fileMonitorEntries.Add(new FileMonitor {
                            FileName = e.Name,     // Here is the Exception 
                            FilePath = e.FullPath  //
                        });
                    };

                    // Deleted
                    _fileSysWatcher.Deleted += (sender, e) => {

                        _fileMonitorEntries.Add(new FileMonitor {
                            FileName = e.Name,
                            FilePath = e.FullPath
                        });
                    };

                  _fileSysWatcher.EnableRaisingEvents = true;
                }
            }

            lstFileMonitorEntries.ItemsSource = _fileMonitorEntries;
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
    }  

这是XML代码

            <ListBox Name="lstFileMonitorEntries" Height="358" Canvas.Left="292" Canvas.Top="10" Width="482" Background="#FF252222">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding FileName}" FontSize="15" FontFamily="Segeo WP Light" Foreground="White"/>
                            <TextBlock Text="{Binding FilePath}" FontSize="14" FontFamily="Segeo WP Light" Foreground="Red" />

                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

有没有人知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

您在这里面对thread affinity issueObservableCollection绑定到UI元素cannot be modified from other than UI thread

并且CreatedDeleted事件为called on background thread,因此不允许从该线程进行任何集合更新。

您需要delegate them on UI dispatcher才能获得execute on UI thread。可以使用App.Current.Dispatcher访问UI调度程序。这是如何完成的 -

_fileSysWatcher.Created += (sender, e) =>
      {
          App.Current.Dispatcher.Invoke((Action)delegate
          {
              _fileMonitorEntries.Add(new FileMonitor
              {
                 FileName = e.Name,
                 FilePath = e.FullPath
              });
          });
      };

同样在UI调度程序中委托delete事件中的代码。