2012-11-17 36 views
0

我的應用程序是WPF threadsave觀察到的集合項目變更事件

好爲每個下載即時顯示進度,我想一個基本的下載應用程序,允許用戶互相下載文件(一個非常基本的Kazaa的:-))它根據真實的下載進度更新。

我有一個observablecollection,它包含一個包含progress屬性的downloadInstance對象。

一旦我更新進度屬性,observablecollection更改事件可能不會被觸發,並且進度條保持不變而沒有任何可視化進度。

這裏是我的threadsaveobservablecollection類

public class ThreadSafeObservableCollection<T> : ObservableCollection<T> 
{ 
    public override event NotifyCollectionChangedEventHandler CollectionChanged; 

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
     NotifyCollectionChangedEventHandler CollectionChanged = this.CollectionChanged; 
     if (CollectionChanged != null) 
      foreach (NotifyCollectionChangedEventHandler nh in CollectionChanged.GetInvocationList()) 
      { 
       DispatcherObject dispObj = nh.Target as DispatcherObject; 
       if (dispObj != null) 
       { 
        Dispatcher dispatcher = dispObj.Dispatcher; 
        if (dispatcher != null && !dispatcher.CheckAccess()) 
        { 
         dispatcher.BeginInvoke(
          (Action)(() => nh.Invoke(this, 
           new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))), 
          DispatcherPriority.DataBind); 
         continue; 
        } 
       } 
       nh.Invoke(this, e); 
      } 
    } 

} 

這是初始化過程

uploadActiveInstances = new ThreadSafeObservableCollection<instance>(); 
instance newInstance = new instance() { File = file, User = user }; 
uploadActiveInstances.Add(newInstance); 

,並終於在這裏被我的實例類

public class instance 
{ 
    public FileShareUser User { get; set; } 
    public SharedFile File { get; set; } 
    public int Progress { get; set; } 
} 

我怎樣才能提高改變事件一次實例的屬性更改(progress ++)?

回答

1

ObservableCollection將在IT更改(例如添加/刪除項目)時引發一個事件,但當它保存的項目更改時,則不會引發該事件。

要在事件發生變化時發出事件,您的instance類必須實現INotifyPropertyChanged接口。

例如:

public class instance : INotifyPropertyChanged 
{ 
    private int progress; 
    public int Progress 
    { 
     get { return progress; } 
     set 
     { 
      if (progress != value) 
      { 
       progress = value; 
       if (PropertyChanged != null) 
       { 
        PropertyChanged(this, new PropertyChangedEventArgs("Progress")); 
       } 
      } 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    /* Do the same with the remaining properties */ 
    public string User { get; set; } 
    public string File { get; set; } 

} 

你會看到,現在,當你改變它會在用戶界面得到更新的進展。
在上面的代碼中,因爲我沒有爲UserFile提高PropertyChanged事件,所以當您更改它們時,它們將不會在UI中更新。

+0

感謝該訣竅:-) –

0

Observablecollection僅在添加或刪除項目時更新可視化樹 這就是爲什麼當您更改項目值時,它不會被重新渲染。

變化的進展屬性是一個依賴屬性,綁定進度條「值」屬性 或實現INotifyPropertyChanged接口