ListView源没有从NavigationParameters更新
本文关键字:NavigationParameters 更新 ListView | 更新日期: 2023-09-27 18:11:55
这是我的代码在我的Xamarin表单应用程序,它应该填充与DetaledActivity
的Activities
列表从上一页填充的xaml ListView。当我逐步执行和调试代码时,_activities
包含许多项目,但它们没有显示在xaml页面中。
如果我在此页面的构造函数中使用项目填充列表,那么我可以单击这些单元格,但其中没有显示文本。
public class DetailedActivityPageViewModel : _ViewModelBase
{
INavigationService _navigationService;
public DetailedActivityPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
}
public override void OnNavigatedTo(NavigationParameters parameters)
{
base.OnNavigatedTo(parameters);
if (parameters.ContainsKey("properties"))
{
var localAcs = new List<DetailedActivity>();
var properties = (Dictionary<string, object>)parameters["properties"];
foreach (var prop in properties)
{
if (prop.Value != null)
localAcs.Add(new DetailedActivity { Key = prop.Key.ToString(), Value = prop.Value.ToString() });
}
_activities = localAcs;
}
}
private IEnumerable<DetailedActivity> _activities;
public IEnumerable<DetailedActivity> Activities { get { return _activities; } set { SetProperty(ref _activities, value, "Activities"); } }
}
public class DetailedActivity
{
public string Key;
public string Value;
}
<ListView ItemsSource="{Binding Activities}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Key}" />
<Label Text="{Binding Value}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我会尝试使用localAcs
的ObservableCollection
而不是List
。对于ObservableCollection
,当向ObservableCollection
添加或删除元素时,应该更新绑定。在添加元素之前,您可能需要将_activities
设置为' localAcs',例如:
public override void OnNavigatedTo(NavigationParameters parameters)
{
base.OnNavigatedTo(parameters);
if (parameters.ContainsKey("properties"))
{
var localAcs = new List<DetailedActivity>();
_activities = localAcs;
var properties = (Dictionary<string, object>)parameters["properties"];
foreach (var prop in properties)
{
if (prop.Value != null)
localAcs.Add(new DetailedActivity { Key = prop.Key.ToString(), Value = prop.Value.ToString() });
}
}
}