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。
我在做什麼錯?
我沒有看到你在哪裏創建集合。您可能在綁定執行後創建它,因此您需要發出PropertyChanged事件來通知UI。 (雖然我不熟悉Galasoft.MvvmLight。) –
爲什麼你需要(想)一個'async void'方法中的Dispatcher.RunAsync?有些東西沒有味道。 –
我在ViewModel構造函數中創建了Collection。 Dispatcher.RunAsync允許該指令在UI線程上運行,不是嗎? –