如何在另一个xaml中获取文本框的文本到文本块? c#windows商店应用

我的MainPage.xaml中的代码

 

我的MainPage.xaml.cs中的代码

 public string TextBox1Text { get { return this.txtBox1.Text; } set { this.txtBox1.Text = value; } } 

我的Page2.xaml中的代码

 MainPage main = new MainPage(); protected override void OnNavigatedTo(NavigationEventArgs e) { txtBlock1.Text = main.TextBox1Text; } 

当我运行它时,我的文本块中没有输出文本

一种更简单的方法是在页面之间传递参数:

MainPage.xaml.cs

 private void Button_Click(object sender, RoutedEventArgs e) { Frame.Navigate(typeof(Page2), textBox1.Text); } 

Page2.xaml.cs

 protected override void OnNavigatedTo(NavigationEventArgs e) { textBlock1.Text = e.Parameter.ToString(); } 

编辑 :您似乎想要传递多个参数。 您可以在List集合中打包多个对象或创建一个类:

 public class NavigationPackage { public string TextToPass { get; set; } public ImageSource ImgSource { get; set; } } 

在您当前的页面中:

 private void Button_Click(object sender, RoutedEventArgs e) { NavigationPackage np = new NavigationPackage(); np.TextToPass = textBox1.Text; np.ImgSource = bg2.Source; Frame.Navigate(typeof(MultiGame), np); } 

MultiGame.cs您可以“解包”该类中的项目:

 protected override void OnNavigatedTo(NavigationEventArgs e) { NavigationPackage np = (NavigationPackage)e.Parameter; newTextBlock.Text = np.TextToPass; newImage.Source = np.ImgSource; } 

您正在创建MainPage的新实例。 TextBox1Text未使用值初始化。

如果您希望它是所有页面共享的值,请创建静态类或在App.cs文件中声明您的属性

这与说法相同。

 MyCustomClass x = new MyCustomClass(); x.StringProperty = "Im set"; x = new MYCustomClass(); 

x.StringProperty现在没有设置。