2016-12-12 53 views
0

我有一個ViewModel來擴展Galasoft.MvvmLight.ViewModelBase。在這裏面我有這樣的:MVVMLIght中的可觀察集合不會更新UI

public ObservableCollection<Association> Delegation { get; set; } 

    private async void LoadDelegations() 
    { 
     Delegation.Clear(); 
     var delegations = await NetworkManager.GetDelegations(); 
     if(delegations== null) 
     { 
      return; 
     } 
     for (int i = 0;i< delegations.Count;i++) 
     { 
      Delegation.Add(delegations[i]); 
     } 
    } 

    private async void RemoveDelegation(string delegationId) 
    { 
     var response = await NetworkManager.RemoveDelegation(delegationId); 
     if (response.Result) 
     { 
      int i; 
      for (i = 0; i < Delegation.Count; i++) 
      { 
       if (Delegation[i].Id == delegationId) break; 
      } 

      await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
      { 
       Delegation.RemoveAt(i); 
      }); 
     } 
    } 

此屬性綁定到ListView:

<ListView ItemTemplate="{StaticResource AssociationTemplate}" 
      ItemsSource="{Binding Delegation}"/> 

我的問題是LoadDelegation更新UI只是偶爾,而不是RemoveDelegation從未更新UI。

我在做什麼錯?

+0

我沒有看到你在哪裏創建集合。您可能在綁定執行後創建它,因此您需要發出PropertyChanged事件來通知UI。 (雖然我不熟悉Galasoft.MvvmLight。) –

+0

爲什麼你需要(想)一個'async void'方法中的Dispatcher.RunAsync?有些東西沒有味道。 –

+0

我在ViewModel構造函數中創建了Collection。 Dispatcher.RunAsync允許該指令在UI線程上運行,不是嗎? –

回答

0

我不確定MVVM-Light過程,但在MVVM模式中,這裏的問題是您正在使用自動實現的屬性。所以自動實現的屬性不會引發INotifyPropertyChanged事件。您可以簡單地更改委派的自動實施屬性。您可以通過`private ObservableCollection委託將其更改爲完整的屬性;

public ObservableCollection<Association> Delegation 
    { 
     get { return delegation; } 
     set { delegation = value; RaisePropertyChanged("Delegation")} 
    }` 

雖然RaisePropertyChanged是多數民衆贊成儘快屬性更改打來電話,讓視圖知道這件事的方法。而MVVM-Light只是提供實現INotifyPropertyChanged接口的基類