【问题标题】:Xamarin Refresh Collection from ViewModel from another class来自另一个类的 ViewModel 的 Xamarin 刷新集合
【发布时间】:2021-08-22 16:48:57
【问题描述】:

从 Xamarin.Forms 中的另一个类向 ViewModel 中的 ObservableCollection 添加/删除对象的最佳方法是什么?

假设我有一个“事物”类型的集合。 Thing 模型包含名称和描述作为字符串。

现在我想将另一个页面中的“事物”对象添加到此集合中。

有什么办法?

【问题讨论】:

  • 请避免要求“最好”或“更好”,这是见仁见智的问题。
  • 有很多方法可以做到这一点。您可以将整个 ObservableCollection 传递到第二页。您可以在第一页上创建新对象并将其传递到第二页以填充值。添加对象时,您可以使用 MessagingCenter 将消息从第二页传递到第一页。
  • 嗨@Jason,感谢您的意见。我试图将整个集合传递到第二页,但无法使用 Xamarin Shell 和 QueryProperties。
  • 如果您使用的 Shell 将无法正常工作。我会尝试消息中心
  • 创建模板 xamarin.forms 解决方案,其中显示了一种方法。

标签: c# xamarin xamarin.forms


【解决方案1】:

Xamarin.Forms MessagingCenter 类实现了发布-订阅模式,允许在不方便通过对象和类型引用链接的组件之间进行基于消息的通信。 您可以使用 MessagingCenter.Send 将对象发送到页面并使用 MessagingCenter.Subscribe 接收它。 以下是我在新示例 shell 应用中的操作:

显示页面:

     public partial class DisplayPage : ContentPage
        {
            public static ObservableCollection<People> mycol = new ObservableCollection<People>();
            public DisplayPage()
            {
                InitializeComponent();
                People p1 = new People("Adam", 20);
                People p2 = new People("Bob", 22);
                People p3 = new People("Candy", 39);
                mycol.Add(p1);
                mycol.Add(p2);
                mycol.Add(p3);
                //recieve message
                MessagingCenter.Subscribe<OperatePage, People>(this, "message",  (sender, arg) =>
                {
                    mycol.Add(arg);
                });
                col.ItemsSource = mycol;
    
            }
        }

发送对象:

  protected void onButtonClicked(Object sender, EventArgs e)
        {
            string name = inputname.Text;
            int age = Int16.Parse(inputage.Text);
            People newguy = new People(name,age);
            MessagingCenter.Send<OperatePage, People>(this, "message", newguy);

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多