Search code examples
c#xamlwindows-8windows-store-apps

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


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


Solution

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