首页 文章

UWP,在Windows之间传递信息

提问于
浏览
2

在UWP项目中,我试图在两个窗口之间传递信息 . 单击某个项目将基本打开另一个包含更多详细信息的XAML页面 . 我没有导航,因为我不希望主页消失 .

代码如下,它按预期工作 . XAML打开,我可以看到所有控件和代码按预期运行 . 基本上我想在Detail.xaml文件中预先填充一些文本块 .

CoreApplicationView newView = CoreApplication.CreateNewView();
int newViewId = 0;
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    Frame frame = new Frame();
    frame.Navigate(typeof(Detail), null);
    Window.Current.Content = frame;
    Window.Current.Activate();
    newViewId = ApplicationView.GetForCurrentView().Id;
});
bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);

代码取自https://docs.microsoft.com/en-us/windows/uwp/design/layout/show-multiple-views

1 回答

  • 1

    如果在打开辅助视图之前已经显示了要显示的数据,则可以在导航期间轻松地将它们传递到 Detail 视图:

    string data = ...;
    frame.Navigate(typeof(Detail), data);
    

    但是,当您需要在视图之间进行实际通信时,事情变得更加棘手 . UWP中的每个视图都有自己的UI线程和自己的 Dispatcher . 这意味着所有处理UI的代码(如填充控件,更改页面背景等)都需要在给定视图的线程上运行 . 执行此操作的一种方法"communication"是将引用存储到新创建的应用程序视图,或通过 CoreApplication.Views 属性访问它 . 每当您需要操作视图的UI时,您都可以使用调度程序 .

    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        //do something with the secondary view's UI
        //this code now runs on the secondary view's thread
        //Window.Current here refers to the secondary view's Window
    
        //the following example changes the background color of the page
        var frame = ( Frame )Window.Current.Content;
        var detail = ( Detail )frame.Content;
        var grid = ( Grid )detail.Content;
        grid.Background = new SolidColorBrush(Colors.Red);
    }
    

相关问题