TabbedPage内的Xamarin Forms ListView无法使用ObservableCollection更新

问题描述 投票:2回答:3

我的ListView文件的XAML正在填充具有服务中的ViewModelObservableCollection,但ListView没有更新信息。我已经检查了服务是否返回了正确的信息。

XML:

<ListView x:Name="DashboardDetailsList" 
            SelectionMode="None" 
            HasUnevenRows="True" 
            ItemsSource="{Binding DetailsList}"
            BackgroundColor="Transparent" 
            VerticalOptions="FillAndExpand" 
            SeparatorVisibility="None">
   <ListView.ItemTemplate>
       <DataTemplate>
           <ViewCell>
              ...
              ...
           </ViewCell>
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

代码:

public ObservableCollection<Dashboard> DetailsList { get; set; } = new ObservableCollection<Dashboard>();
//API Call
details = await _clientAPI.getDashboardDetails(id);
if (details != null)
{
    DetailsList.Clear();
    foreach (var item in details)
    {
        DetailsList.Add(item);
    }
}
listview mvvm xamarin.forms observablecollection tabbedpage
3个回答
-2
投票

尝试这个人

public ObservableCollection<Dashboard> DetailsList { get; set; } = new ObservableCollection<Dashboard>();
//API Call
details = await _clientAPI.getDashboardDetails(id);
if (details != null)
{
    DetailsList = details;
}

-2
投票

对不起,您正在使用MVVM吗?

您需要通知变量已更改。

喜欢这个

private ObservableCollection <Dashboard> _detailsList;
public ObservableCollection <Dashboard> DetailsList
{
    get => _detailsList;
    private set => SetProperty (ref _detailsList, value);
}

//API Call
details = await _clientAPI.getDashboardDetails(id);
if (details != null)
{
    DetailsList = details;
}

-2
投票

通过使用INotifyPropertyChanged通知您的财产。请参考下面的代码,

public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Model> items;

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Model> Items
    {
        get => items;
        set
        {
            items = value;
            OnPropertyChanged("Items");
        }
    }
}

请参阅有关DataBinding的更多信息

在您的情况下,如果要从API获取列表,则可以像下面这样进行分配,

var details = await _clientAPI.getDashboardDetails(id);
Items = new ObservableCollection<Model>(details);
© www.soinside.com 2019 - 2024. All rights reserved.