2013-11-23 67 views
0

我想从FileSystemWatcher(名称,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> 

没有任何人有什么我做错了的想法?

+0

你的声明是如何声明的? – Dan

+0

你确实意识到你可能会将相同的文件添加到一个集合两次? –

+0

你的意思是2个事件处理程序和属性? – iNCEPTION

回答

0

您正在面临thread affinity issue这里。 ObservableCollection绑定到UI元素cannot be modified from other than UI thread

而且CreatedDeleted事件是called on background thread,因此在收集任何更新不会从该线程允许的。

您需要delegate them on UI dispatcher才能得到execute on UI thread。 UI调度员可以使用App.Current.Dispatcher这怎么是可以做到的访问 -

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

同样委派在UI调度删除事件的代码。