在 Windows 10(通用 Windows 平台)应用程序的页面之间传递数据。 (C# / MVVM)

Passing data between pages in Windows 10 (Universal Windows Platform) application. (C# / MVVM)

观看次数:

  1. SinglePersonView.xaml (datacontext = SinglePersonViewModel.cs) 注意:这也是主页。
  2. HouseView.xaml(数据上下文 = HouseViewModel.cs)

视图模型:

  1. SinglePersonViewModel.cs
  2. HouseViewModel.cs

型号:

  1. Person.cs

在这种假设情况下,我在 SinglePersonViewModel.cs 文件中实例化了一个 Person 对象。我对该对象执行一些操作。我单击按钮导航到 HouseView.xaml。这里的目的是能够在 HouseView.xaml 中看到那个 Person 对象,并且还能够操作它的属性。目的是能够在所有视图中访问和修改此 Person 中的属性。

规则:

  1. 人 class 不能是静态的。
  2. Person 对象一旦创建,就需要可以从所有视图访问。

问题/总结:

页面之间如何传递数据?我应该在 SinglePersonViewModel.cs 以外的其他位置创建 Person 的实例吗?如果是,应该在哪里以及如何实施?

提前致谢。

在 MVVM 模式中,您不仅有 ViewViewModel 部分。作为 ViewModel 的数据源,您应该创建 Model class 来控制您的个人持久性。

例如,您正在 SinglePersonViewModel 中创建或检索 Person 对象。首先你应该调用模型来获得一个实例:

Person = personsModel.Get(personId);

然后你操作人物属性并保存:

personsModel.Save(Person);

现在您打开了 HouseViewModel 并且想要一个人实例。只需调用模型来检索它:

Person = personsModel.Get(personId);

您也可以使用 mvvmlight messenger (or other EventAggregator* 实现来交换来自视图模型的消息。

Here is an example.

发送自SinglePersonViewModel:

// Sends a notification message with a Person as content.
Messenger.Default.Send(new NotificationMessage<Person>(person, "Select"));

HouseView 收到:

// Registers for incoming Notification messages.
Messenger.Default.Register<NotificationMessage<Person>>(this, (message) =>
{
    // Gets the Person object.
    var person = message.Content;

    // Checks the associated action.
    switch (message.Notification)
    {
        case "Select":
            break;
        case "Delete":
            break;
        default:
            break;
    }
});

For low-coupled communication between modules (not only ViewModels) we can try to implement EventAggregator pattern. Event aggregator helps to implement subscriber/publisher pattern in low-coupled app. I know few different implementations.

First one based on CodeProject post and uses WeakReference that will help you to prevent memory leak. I will not publish whole code because you can just download source code and use it. In this implementation you must to implement ISubscriber interface for your subscribers.

The second is Microsoft Prism implementation. This is an open source project then you can see interface, implementation and base event class. In this implementation you must unsubscribe from the event manually.

The third and the last is MVVMLight library and its Messenger class.

As you can see all of this implementations uses Singleton pattern for saving subscribers.