【发布时间】:2021-11-16 09:37:03
【问题描述】:
在标题中,我遇到了一个问题,即更新弹出视图模型中的属性不会更新 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>
所以现在我有两个问题:
- 标签不更新。它绑定到具有 INotifyPropertyChanged 的属性
- 奇怪的是,这个订阅只发生了第二次(之后也是,只是不是第一次)我打开了一个弹出窗口。这是因为它在构造函数中吗?如果是,正确的处理方法是什么?
还有一个小问题 - 我在订阅结束时取消订阅。当我没有它并打印出AnimeGroupObservable [0] .Name时,第一次打印一次,第二次我打开弹出窗口两次等等。最后取消订阅是正确的修复方法吗这个?
【问题讨论】:
-
您正在发送消息,然后创建订阅消息的页面。因此,在发送消息时,没有人在听,它就会消失。您还为发送和订阅使用了错误的语法。在这种情况下,将数据作为参数传递给页面构造函数会简单得多。
-
我理解您所说的大部分内容,但是您将数据作为参数传递到底是什么意思?我知道有一个命令参数术语。页面也是指打开弹出窗口或弹出窗口的页面。最后一件事,通过页面构造函数,您建议使用代码隐藏还是您的意思是视图模型构造函数。那我应该从消息中心辞职吗?清理并详细解释对我有帮助。感谢您的帮助!
标签: xaml xamarin xamarin.forms mvvm xamarin-community-toolkit