在Windows应用商店应用程序中访问当前MainPage实例的最佳方式

本文关键字:MainPage 实例 方式 最佳 访问 应用 Windows 应用程序 | 更新日期: 2023-09-27 18:21:38

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

具体来说,在Surface RT平板电脑的Windows应用商店应用程序中(因此,仅限于RT API),我希望访问其他类的主页面方法和UI元素。

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

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

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

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

在Windows应用商店应用程序中访问当前MainPage实例的最佳方式

我同意使用MVVM模式更好,但如果您需要获取当前页面,可以按如下方式进行:

  var frame = (Frame)Window.Current.Content;
  var page = (MainPage)frame.Content;

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

主窗口.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:

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

非常简单…:)

我更喜欢Delegate/Event,这样您就无法直接访问该类。

public MainWindow()
{
    StartWindowUserControl.newBla += StartWindowUserControl_newBla;
    private void StartWindowUserControl_newBla()
    {

public partial class StartWindowUserControl : UserControl
{
    public delegate void newBlaDelegate();
    public static event newBlaDelegate newBla;
MethodA()
{
   new();