Windows应用商店应用XAML - 如何获取导航页面的文本框值

时间:2016-10-18 14:17:57

标签: c# xaml windows-store-apps windows-10-universal windows-store

Windows应用商店应用XAML - 如何获取导航页面的文本框值.i有2页 1.MainPage.xaml 2.Infopage.xaml 在MainPage中我有一个Button(获取InfoPage的TextBox值)和一个框架(以导航InfoPage).. 在InfoPage中有一些TextBoxes ..现在我如何获得InfoPage TextBox值

2 个答案:

答案 0 :(得分:1)

除了Neal的解决方案之外,还有两种方法可供您参考。

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

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 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(); } }

infoPage

如果您有大量数据,更好的方法是将本地文件创建为数据库,并使用MVVM模式将数据从MainPage写入本地文件,并将保存在数据库中的数据绑定到String peopleDate = cursor.getString(cursor.getColumnIndex(PEOPLE_DATE)); String peopleMonth = cursor.getString(cursor.getColumnIndex(PEOPLE_MONTH)); String peopleYear = cursor.getString(cursor.getColumnIndex(PEOPLE_YEAR)); 。有关MVW的更多详细信息,请参阅ApplicationData.LocalSettings

答案 1 :(得分:0)

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

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

public string commonValue;

在InfoPage中

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

在后面的InfoPage代码中,我们将文本框的值存储到应用程序。

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

然后在MainPage中:

    <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;
    }
}