ObservableCollection不更新

ObservableCollection不更新

本文介绍了Xamarin表单ListView ObservableCollection不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ListView绑定到由viewModels组成的ObservableCollection.

I have a ListView that is bound to an ObservableCollection composed of viewModels.

viewModel看起来像这样:

the viewModel looks like this:

public string Id{ get; set; }
public string Name{ get; set; }
public bool HasId
{
    get { return !(String.IsNullOrEmpty(Id)); }
}

在前端xaml中:

<ListView x:Name="MyList" ItemsSource="{Binding MyList}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <StackLayout>
          <Label Text="{Binding Name" FontSize="Small"/>
          <StackLayout Spacing="20">
            <Entry Text="{Binding Id}"/>
            <Button Text="Create Profile" IsEnabled="False">
              <Button.Triggers>
                <DataTrigger TargetType="Button" Binding="{Binding HasId}" Value="True">
                  <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
              </Button.Triggers>
            </Button>
          </StackLayout>
        </StackLayout>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

所需结果:当用户键入条目(绑定到Id)时,应启用该按钮.

Desired Result: when user types into entry (binded to Id), the button should be enabled.

实际结果:当用户键入条目时,什么也没发生(我猜是因为ObservableCollectionviewmodel中看不到更改)

Actual Result: when user types into entry, nothing happens (I'm guessing cause the ObservableCollection does not see the change within the viewmodel)

注意:当我向ObservableCollection添加元素或从中删除元素时,视图确实会更新(按预期).

Note: When I add/delete an element to/from the ObservableCollection, the view does update (as expected).

任何建议/想法都将不胜感激!

Any suggestions/ideas are greatly appreciated!

推荐答案

您需要在viewmodel类上实现INotifyPropertyChanged.

You need to implement INotifyPropertyChanged on the viewmodel class.

ObservableCollection<T>类仅处理有关集合本身是否已更改的通知-添加/删除项等.它不处理有关何时更改各个项目本身的属性的通知.

The ObservableCollection<T> class only handles notifications regarding whether the collection itself has changed - items added/removed/etc. It does not deal with notifications for when properties of the individual items themselves are changed.

这篇关于Xamarin表单ListView ObservableCollection不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:48