Windows Store App XAML - 如何获取导航页面的文本框值

Windows Store App XAML - How to get textbox value of navigated page

Windows Store App XAML - 如何获取导航的文本框值 page.i 有 2 个页面 1.MainPage.xaml 2.Infopage.xaml 在 MainPage 中,我有一个按钮(用于获取 InfoPage 的 TextBox 值)和一个框架(用于导航 InfoPage).. 在 InfoPage 中有一些 TextBoxes..现在我怎样才能获得 InfoPage TextBox 值

最简单的方法是将 InfoPage 中的值存储到 App 对象中的全局变量中,然后在 MainPage 中检索它。

在app.xaml.cs中定义一个字符串或List,

public string commonValue;

在信息​​页中

    <StackPanel Orientation="Vertical" VerticalAlignment="Center" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox Name="tb1" Text="Hello"/>

在后面的InfoPage代码中,我们将textbox的值存储到app中。

        public InfoPage()
    {
        this.InitializeComponent();
        App app = Application.Current as App;
        app.commonValue = tb1.Text;
    }

然后在主页中:

    <StackPanel VerticalAlignment="Center" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Content="MainPage" Click="Button_Click"/>
    <TextBox Name="textbox1"/>

在后面的 MainPage 代码中,我们需要初始化 InfoPage 然后检索值:

    public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        InfoPage info = new InfoPage();
        info.InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        App app = Application.Current as App;
        textbox1.Text = app.commonValue;
    }
}

除了Neal的解决方法,这里还有另外两种方法你也可以参考。

一种方法是在infoPage 上定义一个静态参数并将该值设置为当前页面。然后您可以从 MainPage 调用 infoPage 上的方法。代码如下:

infoPage

 public static InfoPage Current;
 public InfoPage()
 {
     this.InitializeComponent();
     Current = this;      
 }
public string gettext()
{
    return txttext.Text;
}

MainPage

private void btngetsecondpage_Click(object sender, RoutedEventArgs e)
{
    InfoPage infopage = InfoPage.Current;
    txtresult.Text = infopage.gettext();  
}

更多关于ApplicationData的细节请参考official sample

另一种方法是在 infoPage 上将文本临时保存在 ApplicationData.LocalSettings 中,然后在 MainPage 上读出文本。代码如下:

infoPage

private void txttext_TextChanged(object sender, TextChangedEventArgs e)
{
    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
    localSettings.Values["texboxtext"] =txttext.Text; // example value            
}

MainPage

 private void btngetsecondpage_Click(object sender, RoutedEventArgs e)
 { 
     ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
     if (localSettings.Values["texboxtext"] != null)
     {
         txtresult.Text = localSettings.Values["texboxtext"].ToString();
     }
 }

如果你有大量数据,更好的方法是创建一个本地文件作为数据库,并使用MVVM模式将数据从infoPage写入本地文件并绑定保存在数据库到 MainPage。更多关于 uwp 中 MVVM 的细节你可以参考 this article .