2014-03-18 76 views
0

我將ViewModel中的observablecColletion綁定到View中的組合框(使用MVVM Caliburn.Micro)。 obsevableColletion從一個字符串數組中獲取它的項目,該數組獲取目錄中的文件名。所以我的問題是:當我添加或刪除目錄中的文件時,如何使組合框自動更新?更新綁定到可觀察集合的Combobox

這裏是我的代碼: 視圖模型

private ObservableCollection<string> _combodata; 
Public ObservableCollection<string> ComboData 
{ 
    get 
    { 
     string[] files = Directory.GetFiles("C:\\Documents"); 
     _combodata = new ObservableCollection<string>(files); 
     return _combodata; 
    } 
    set 
    { 
     _combodata = value; 
     NotifyOfPropertyChange(() => ComboData); 
    } 
} 

查看:

<ComboBox x:name = "ComboData" ......../> 
+0

每當項目被添加到目錄中時,您也必須將其添加到ObservableCollection組合數據中。 –

回答

1

例這裏有一個視圖模型,你想要做什麼。它使用FileSystemWatcher來檢測文件系統中的更改。它使用DispatcherFileSystemWatcher事件封送回UI線程(您不想在後臺線程上更改ObservableCollection)。當你完成這個視圖模型時,你應該調用Dispose

public class ViewModel : IDisposable 
{ 
    // Constructor. 
    public ViewModel() 
    { 
     // capture dispatcher for current thread (model should be created on UI thread) 
     _dispatcher = Dispatcher.CurrentDispatcher; 

     // start watching file system 
     _watcher = new FileSystemWatcher("C:\\Documents"); 
     _watcher.Created += Watcher_Created; 
     _watcher.Deleted += Watcher_Deleted; 
     _watcher.Renamed += Watcher_Renamed; 
     _watcher.EnableRaisingEvents = true; 

     // initialize combo data 
     _comboData = new ObservableCollection<string>(Directory.GetFiles(_watcher.Path)); 
     ComboData = new ReadOnlyObservableCollection<string>(_comboData); 
    } 

    // Disposal 
    public void Dispose() 
    { 
     // dispose of the watcher 
     _watcher.Dispose(); 
    } 

    // the dispatcher is used to marshal events to the UI thread 
    private readonly Dispatcher _dispatcher; 

    // the watcher is used to track file system changes 
    private readonly FileSystemWatcher _watcher; 

    // the backing field for the ComboData property 
    private readonly ObservableCollection<string> _comboData; 

    // the ComboData property should be bound to the UI 
    public ReadOnlyObservableCollection<string> ComboData { get; private set; } 

    // called on a background thread when a file/directory is created 
    private void Watcher_Created(object sender, FileSystemEventArgs e) 
    { 
     _dispatcher.BeginInvoke(new Action(() => _comboData.Add(e.FullPath))); 
    } 

    // called on a background thread when a file/directory is deleted 
    private void Watcher_Deleted(object sender, FileSystemEventArgs e) 
    { 
     _dispatcher.BeginInvoke(new Action(() => _comboData.Remove(e.FullPath))); 
    } 

    // called on a background thread when a file/directory is renamed 
    private void Watcher_Renamed(object sender, RenamedEventArgs e) 
    { 
     _dispatcher.BeginInvoke(new Action(() => 
      { 
       _comboData.Remove(e.OldFullPath); 
       _comboData.Add(e.FullPath); 
      })); 
    } 
} 
相關問題