2013-11-23 102 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調度刪除事件的代碼。