2016-12-12 52 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接口的基类