首页 > 解决方案 > 如何在 UWP 应用中的主窗口和 AppWindow 之间传输信息?

问题描述

所以我正在开发一个应用程序,有些项目需要一个属性窗口才能打开。我一直在关注如何使用本指南AppWindow

我无法弄清楚的是如何在主窗口和属性窗口之间推送信息。所以就像它第一次打开时一样,我需要给它所有要显示的存储属性,但是属性窗口需要将任何更改推送回主窗口以进行存储和使用。

我有非常基本的代码,但我认为它展示了我在做什么。

MainPage.xaml.cs:

public sealed partial class MainPage : Page
{

    ...

    public async Task OpenPropertiesWindow()
    {
        //https://docs.microsoft.com/en-us/windows/uwp/design/layout/app-window

        AppWindow properties_appwindow = await AppWindow.TryCreateAsync();
        Frame appWindowContentFrame = new Frame();
        appWindowContentFrame.Navigate(typeof(PropertiesWindow));
        ElementCompositionPreview.SetAppWindowContent(properties_appwindow, appWindowContentFrame);

        properties_appwindow.RequestSize(new Size(300, 400));
        properties_appwindow.Title = "Properties";

        //send data to the textbox in PropertiesWindow

        properties_appwindow.Closed += delegate
        {
            appWindowContentFrame.Content = null;
            properties_appwindow = null;
        };

        await properties_appwindow.TryShowAsync();
    }

属性窗口.xaml:

<Page
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBox x:Name="txtbox_property1" PlaceholderText="property1"/>
            <Button x:Name="btn_apply" Content="Apply" Tapped="ApplyPropertiesButton_Tapped"/>
        </StackPanel>
    </Grid>
</Page>

属性窗口.xaml.cs

public sealed partial class PropertiesWindow : Page
{
    public PropertiesWindow()
    {
        this.InitializeComponent();
    }

    private void ApplyPropertiesButton_Tapped(object sender, TappedRoutedEventArgs e)
    {
        string data_from_txtbox = txtbox_property1.Text;

        //push this data_from_txtbox to MainPage
    }
}

谁能帮我吗?每当更改属性时,我还需要运行另一种更新方法MainPage,因此我需要某种触发器来处理数据被发回的情况。

标签: c#uwpuwp-xaml

解决方案


您可以使用Frame您在导航后创建的以访问Page实例:

var page = (PropertiesWindow)appWindowContentFrame.Content;
//do something with the page, for example
page.SomePublicMethod(myData);

反过来,您可以使用WindowAPI 从AppWindow页面访问主应用程序窗口:

private void ApplyPropertiesButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    string data_from_txtbox = txtbox_property1.Text;

    var rootFrame = (Frame)Window.Current.Content;
    var page = (MainPage)rootFrame.Content;
    page.SomePublicMethod(data_from_txtbox);
}

推荐阅读