来自另一个 class 的 ViewModel 的 Xamarin 刷新集合
Xamarin Refresh Collection from ViewModel from another class
从 Xamarin.Forms 中的另一个 class 对象到 ViewModel 中的 ObservableCollection 的最佳方法是什么?
假设我有一个类型为“Thing”的集合。事物模型包含字符串形式的名称和描述。
现在我想将另一个页面的“Thing”对象添加到此集合中。
有什么方法可以做到?
Xamarin.Forms MessagingCenter class 实现了发布-订阅模式,允许组件之间基于消息的通信,这些通信不方便 link 通过对象和类型引用。
您可以使用 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);
结果:
从 Xamarin.Forms 中的另一个 class 对象到 ViewModel 中的 ObservableCollection 的最佳方法是什么?
假设我有一个类型为“Thing”的集合。事物模型包含字符串形式的名称和描述。
现在我想将另一个页面的“Thing”对象添加到此集合中。
有什么方法可以做到?
Xamarin.Forms MessagingCenter class 实现了发布-订阅模式,允许组件之间基于消息的通信,这些通信不方便 link 通过对象和类型引用。 您可以使用 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);
结果: