在Windows应用商店应用中访问MainPage当前实例的最佳方法? [英] Best way to access current instance of MainPage in a Windows Store app?

查看:57
本文介绍了在Windows应用商店应用中访问MainPage当前实例的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从C#Windows应用商店应用程序中的另一个类访问主页的当前实例.

I was wondering how one could access the current instance of the main page from a different class in a C# Windows Store app.

具体来说,在适用于Surface RT平板电脑的Windows Store应用中(因此,仅限于RT API),我想访问其他类的主页方法和UI元素.

Specifically, in a Windows Store app for a Surface RT tablet (so, limited to RT API) I want to access mainpage methods and UI elements from other classes.

创建新实例的工作原理如下:

Creating a new instance works, like this:

MainPage mp = new MainPage();
mp.PublicMainPageMethod();
mp.mainpageTextBlock.Text = "Setting text at runtime";

,因为它公开了方法/UI元素,但这不是正确的过程.

in that it exposes the methods / UI elements, but this can't be the proper procedure.

在运行时从其他类访问方法和修改主页上的UI元素的最佳实践是什么?有关Windows Phone的几篇文章,但是我似乎找不到Windows RT的任何内容.

What is the best practice for accessing methods and modifying UI elements on the main page at runtime, from other classes? There are several articles about this for Windows Phone but I can't seem to find anything for Windows RT.

推荐答案

如果您使用的是MVVM,则可以使用Messenger类:

If you're using MVVM, you can use the Messenger class:

MainWindow.xaml:

MainWindow.xaml:

using GalaSoft.MvvmLight.Messaging;

public MainWindow()
{
    InitializeComponent();
    this.DataContext = new MainViewModel();
    Messenger.Default.Register<NotificationMessage>(this, (nm) =>
    {
        //Check which message you've sent
        if (nm.Notification == "CloseWindowsBoundToMe")
        {
            //If the DataContext is the same ViewModel where you've called the Messenger
            if (nm.Sender == this.DataContext)
                //Do something here, for example call a function. I'm closing the view:
                this.Close();
        }
    });
}

在ViewModel中,您可以随时调用Messenger或通知您的View:

And in your ViewModel, you can call the Messenger or notify your View any time:

Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "CloseWindowsBoundToMe"));

非常简单...:)

这篇关于在Windows应用商店应用中访问MainPage当前实例的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆