更新弹出窗口视图模型中的属性不会更新 UI



在标题中,我遇到了一个问题,在弹出窗口的视图模型中更新属性不会更新UI。我使用xamarin社区工具包中的弹出窗口。我正在使用一个执行此任务的命令:

async Task ShowPopup()
{
MessagingCenter.Send(AnimeGroupObservable, "AnimeGroups");
Shell.Current.ShowPopup(new MediaListGroupsPopup());
}

它发送一条带有有效载荷的消息并显示弹出窗口。这是弹出式视图模型:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Input;
using OtakuApp.Models;
using Xamarin.Forms;
namespace OtakuApp.ViewModels
{
class MediaListGroupsPopupViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public ObservableCollection<Group> _AnimeGroups = new ObservableCollection<Group>();
public ObservableCollection<Group> AnimeGroups
{
get => _AnimeGroups;
set
{
if (_AnimeGroups == value)
return;
_AnimeGroups = value;
OnPropertyChanged();
}
}
public String _label;
public String label
{
get => _label;
set
{
if (value == _label)
return;
_label = value;
OnPropertyChanged();
}
}

public MediaListGroupsPopupViewModel()
{
MessagingCenter.Subscribe<ObservableCollection<Group>>(this, "AnimeGroups", (AnimeGroupObservable) =>
{
Console.WriteLine(AnimeGroupObservable[0].Name);
label = AnimeGroupObservable[1].Name;
MessagingCenter.Unsubscribe<ObservableCollection<Group>>(this, "AnimeGroups");
});
}
}
}

我正计划有一个标签的小集合视图可供选择。但现在我正在努力更新一个标签,只是为了测试目的,所以你可以想象,我尝试过集合视图,但它不起作用。在代码中手动将_label设置为某个值表明绑定有效。只是由于某种原因没有更新。

弹出xaml文件:

<?xml version="1.0" encoding="utf-8" ?>
<xct:Popup
x:Class="OtakuApp.Popups.MediaListGroupsPopup"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
Size="300,300">
<StackLayout>
<Label Text="{Binding label}" />
</StackLayout>
</xct:Popup>

所以现在我有两个问题:

  1. 标签不更新。它绑定到具有INotifyPropertyChanged的属性
  2. 奇怪的是,这个订阅只发生在我打开弹出窗口的第二次(之后也是,只是不是第一次)。这是因为它在构造函数中吗?如果是,正确的处理方法是什么

还有一个小问题-我在订阅结束时取消订阅。当我没有它的时候,我打印出了AnimeGroupObservable[0]。名称,第一次打印一次,第二次打开弹出窗口两次等等。最后取消订阅是解决这个问题的正确方法吗?

由于您将单个参数传递到单个页面,因此使用构造函数将比MessagingCenter简单得多(这很好,但在这种情况下过于夸张)

创建页面时,在构造函数中传递参数

Shell.Current.ShowPopup(new MediaListGroupsPopup(AnimeGroupObservable));

然后修改页面构造函数以接受参数

public MediaListGroupsPopup(ObservableCollection<Group> groups)
{
// you did't show how you create your VM, but I assume it's something like this
this.BindingContext = new MediaListGroupsPopupViewModel(groups);
}

然后修改VM构造函数

public MediaListGroupsPopupViewModel(ObservableCollection<Group> groups)
{
label = groups[1].Name;
}

如果你真的只使用一个string值,你可以直接传递它,而不是整个ObservableCollection

最新更新