Dan*_*son 17 c# windows-store-apps
我想知道如何从C#Windows Store应用程序中的不同类访问主页面的当前实例.
具体来说,在Surface RT平板电脑的Windows应用商店应用中(因此,仅限于RT API),我想访问其他类的主页方法和UI元素.
创建一个新实例的工作原理如下:
MainPage mp = new MainPage();
mp.PublicMainPageMethod();
mp.mainpageTextBlock.Text = "Setting text at runtime";
Run Code Online (Sandbox Code Playgroud)
因为它暴露了方法/ UI元素,但这不是正确的过程.
在运行时从其他类访问主页上的方法和修改UI元素的最佳实践是什么?有几篇关于Windows Phone的文章,但我似乎无法为Windows RT找到任何东西.
tak*_*gen 40
我同意使用MVVM模式更好,但是如果你需要获取当前页面,你可以按如下方式进行:
var frame = (Frame)Window.Current.Content;
var page = (MainPage)frame.Content;
Run Code Online (Sandbox Code Playgroud)
如果您使用 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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
在你的 ViewModel 中,你可以随时调用 Messenger 或通知你的 View:
Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "CloseWindowsBoundToMe"));
Run Code Online (Sandbox Code Playgroud)
挺容易... :)
| 归档时间: |
|
| 查看次数: |
11883 次 |
| 最近记录: |