How to get the text of textbox to textblock in another xaml? c# windows store app

≡放荡痞女 提交于 2020-01-13 20:24:46

问题


Code in my MainPage.xaml

<TextBox x:Name="txtBox1" HorizontalAlignment="Left" 
        Margin="376,350,0,0" TextWrapping="Wrap" 
        VerticalAlignment="Top" Height="14" Width="113" 
        Text="{Binding TextBox1Text}"/>

Code in my MainPage.xaml.cs

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

Code in my Page2.xaml

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

when i run this there no text that output in my textblock


回答1:


A simpler way to do that is to pass parameters between pages:

MainPage.xaml.cs:

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

And in Page2.xaml.cs:

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

Edit: It appears that you want to pass multiple parameters. You can package multiple objects in a List<T> collection or create a class:

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

In your current page:

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

In MultiGame.cs you can "unpack" the items from the class:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    NavigationPackage np = (NavigationPackage)e.Parameter;

    newTextBlock.Text = np.TextToPass;
    newImage.Source = np.ImgSource;
}



回答2:


You are creating a new instance of MainPage. TextBox1Text isn't initialized with a value.

If you want it to be a value shared across all of your pages either create a static class or declare your property in the App.cs file

This would be the same as saying.

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

x = new MYCustomClass();

x.StringProperty isn't set now.



来源:https://stackoverflow.com/questions/20884096/how-to-get-the-text-of-textbox-to-textblock-in-another-xaml-c-sharp-windows-sto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!