21

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 に関する記事は見つかりません。

4

3 に答える 3

1

MVVM を使用している場合は、Messenger クラスを使用できます。

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 に通知したりできます。

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

とても簡単... ​​:)

于 2013-07-10T13:59:50.330 に答える
-1

クラスに直接アクセスできないように、デリゲート/イベントを好みます。

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();
于 2013-07-09T19:33:41.723 に答える