我花了很多时间寻找解决方案共享虚拟机之间的物体,我来到了一个成功的解决方案中,但不完全是最优雅:传递一个对象到VM视图
比方说,我想要从VM1发送V1中显示的TestClass类的_testObject对象,该DataContext显然是VM1到VM2,并将其显示在视图V2中。
public class VM1: ViewModelBase
{
...
public VM1()
{
...
Messenger.Default.Register <bool> (this, "isLoaded" t => Messenger.Default.Send<TestClass> (_testObject "myObject"));
}
...
}
public partial class V2: PhoneApplicationPage
{
public V2()
{
InitializeComponent();
}
protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
{
Messenger.Default.Register <TestClass> (this.DataContext "myObject", mo => (this.DataContext and VM2). PropertyInVM2 = mo);
Messenger.Default.Send <bool> (true, "isLoaded");
base.OnNavigatedTo (e);
}
protected override void OnNavigatedFrom (System.Windows.Navigation.NavigationEventArgs e)
{
Messenger.Default.Unregister <TestClass> (this.DataContext "myObject");
base.OnNavigatedFrom (e);
}
}
因此,如果应用程序导航到V2,它等到创建的页面,然后将其在VM1捕捉消息“isLoaded”,然后VM1发送一条消息,你需要VM2的对象。
不,我不喜欢这种方式,我不想在代码bihnd。任何人都可以建议我更优雅的方式?