Search code examples
c#wpftextboxtextblock

Using textbox input in another window?


So i have been searching for an answer to my problem but i couldn't find anything helpful.

The problem is that i want the user to enter a name into a textbox and then pressing a button that opens a new window which will display the chosen name in a textblock.

i have tried using binding in my second window on the textblock:

{Binding Path=text, ElementName=TName}

and TName was the only one that was shown... nothing from the first window what i wanted. so i'm kind of confused on how to use the input from the textbox from the first window.

<TextBox x:Name="TIName" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="Name" Width="120" Height="23" VerticalAlignment="Top"/>

this is what i use on my first window and:

<TextBlock x:Name="TName" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="{Binding Path=text, ElementName=TName} " VerticalAlignment="Top">

is what i have on my second window.

and this is the code behind the button on the first window:

private void Submit_Click(object sender, RoutedEventArgs e)
    {
        var test= new test();

        this.Close();
        test.Show();
    }

Thanks in advance:) any help will be welcome.


Solution

  • You can't do that via binding. The elements in each window and their names are scoped to the window they're defined in; the contents of each window can have no knowledge of each other.

    However, this should work:

    private void Submit_Click(object sender, RoutedEventArgs e)
    {
        var test = new test();
    
        test.TName.Text = this.TIName.Text;
    
        this.Close();
        test.Show();
    }
    

    This binding:

    {Binding Path=text, ElementName=TName}
    

    Would be correct if both TName and TIName were in the same window, but with two small fixes: Property names in bindings are case-sensitive, and the Text property starts with an upper-case T. No property named text (all lower-case) exists on that control. Secondly, the TextBox is named TIName, not TName.

    It would have to be like this:

    {Binding Path=Text, ElementName=TIName}
    

    But again, only if both controls were in the same window, which is not the case here.