【问题标题】:How to transfer information between the main window and an AppWindow in a UWP app?如何在 UWP 应用中的主窗口和 AppWindow 之间传输信息?
【发布时间】:2020-06-20 20:14:08
【问题描述】:

所以我正在开发一个应用程序,有些项目需要一个属性窗口才能打开。我一直在关注this guide 如何使用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();
    }

PropertiesWindow.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>

PropertiesWindow.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 上运行另一个更新方法,因此我需要某种触发器来处理数据被发回的情况。

【问题讨论】:

  • Frame.Navigate 采用可选的 secomd 参数,该参数是传递给页面的对象。您可以使用它将 MainPage 传递给 PropertiesWindow。然后,PropertiesWindow 可以将自身 (this) 传递给 MainPage 上的方法,让 MainPage 知道与谁交谈。

标签: c# uwp uwp-xaml


【解决方案1】:

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

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

反过来,您可以使用Window API 从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);
}

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 2021-06-20
    • 2023-03-10
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多