Xaml Xamarin表单-对ObservableCollection的更改不会更新视图
我有一个ViewModel,当执行命令时,它从服务中获取项目,并将这些项目添加到ObservableCollection。 ObservableCollection绑定到ListView 我的问题是,向ObservableCollection添加项不会自动更新视图-ListView保持为空。如果我调用了OnPropertyChanged(nameof(ItemList)),那么ListView会被更新,但是ObservableCollection不应该处理这个问题吗 我使用的是最新的Xamarin.Forms(2.3.4.247)。这个问题只会影响Android——如果我在iOS上运行,它就会正常工作 实现INotifyPropertyChanged的视图模型:Xaml Xamarin表单-对ObservableCollection的更改不会更新视图,xaml,xamarin,xamarin.forms,Xaml,Xamarin,Xamarin.forms,我有一个ViewModel,当执行命令时,它从服务中获取项目,并将这些项目添加到ObservableCollection。 ObservableCollection绑定到ListView 我的问题是,向ObservableCollection添加项不会自动更新视图-ListView保持为空。如果我调用了OnPropertyChanged(nameof(ItemList)),那么ListView会被更新,但是ObservableCollection不应该处理这个问题吗 我使用的是最新的Xamari
public class ListViewModel : ViewModelBase
{
private readonly IService m_Service;
public ListViewModel(IService service)
{
m_Service = service;
ItemList = new ObservableCollection<Item>();
RefreshCommand = new Command(async () => await RefreshData());
}
public ICommand RefreshCommand {get;set;}
public ObservableCollection<Item> ItemList { get; private set; }
private async Task RefreshData()
{
ItemList.Clear();
var newItems = await m_Service.GetItems();
if(newItems != null) {
foreach(var n in newItems)
{
ItemList.Add(new ItemViewModel() { Title = n.Title });
}
}
}
public class ItemViewModel : ViewModelBase
{
private string m_JobTitle;
public ItemViewModel()
{
}
public string Title
{
get { return m_Title; }
set
{
m_Title = value;
OnPropertyChanged(nameof(Title));
}
}
}
“列表”视图:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:ui="clr-namespace:Test.Mobile.UI;assembly=Test.Mobile.UI"
x:Class="Test.Mobile.UI.MyListView">
<ContentView.Content>
<StackLayout Orientation="Vertical">
<ListView ItemsSource="{Binding ItemList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ui:ItemView></ui:ItemView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentView.Content>
</ContentView>
“项目”视图:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:enums="clr-namespace:Test.Mobile.Models.Enums;assembly=Test.Mobile.Models"
x:Class="Test.Mobile.UI.JobItemView">
<ContentView.Content>
<Label Text={Binding Title}/>
</ContentView.Content>
</ContentView>
您使用的是什么版本的Xamarin表单
- 将项目更新至最新版本
- 如果仍然存在问题,请在添加所有元素后尝试以下操作: ItemList=新的ObservableCollection(新项目)李>
- 如果这不起作用,则可能是ViewModelBase中的一个问题。 对于Handle Property Changed,我使用这个漂亮的包
observedcollection模块
propertyPageModel类上的ty。我将PageModel初始化为继承ViewModelBase(Prism)的ViewModel类上的Model。Module有一个属性isLocked
。如果我更新Model.Modules[0]。isLocked=true
视图不会更新。即使我调用RaisePropertyChanged(nameof(Model.Modules))
,视图仍然没有更新。但是如果我将可观察的收集模块
从PageModel移动到ViewModel,并调用RaisePropertyChanged(模块名称))
,它会更新视图。我做错了什么?