P
P
postya2019-12-13 12:06:53
WPF
postya, 2019-12-13 12:06:53

How to make binding text from textbox to label?

There is a main window in which there is a label with text. When a button is clicked, a window with a textbox opens.
How can I make the text from the second window, when typing, be immediately displayed in the label of the main window?
TextBox of the second window:

<TextBox x:Name="CategoryText"
                     Style="{StaticResource CategoryTextBox}" />

Main window label:
<Label x:Name="CategoryLabel1"
   Grid.Row="1"
   Style="{StaticResource CategoryLabel}">

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
postya, 2019-12-14
@postya

Everything turned out to be much simpler)
in the xaml of the second window there is a special method for changing the text:

<TextBox x:Name="CategoryText"    
 TextChanged="ChangeText"
 Style="{StaticResource CategoryTextBox}" />

in the code of this second window, I wrote this method:
public partial class FontWindow : Window
    {
         private MainWindow window;

        public FontWindow(MainWindow mainWindow)
        {
            InitializeComponent();
            window = mainWindow;
            
        }

       private void ChangeText(object sender, TextChangedEventArgs e)
        {
            TextBox tb = sender as TextBox;
                window.CategoryLabel1.Content = tb.Text;
        }
}

V
valerahex, 2019-12-13
@valerahex

When opening the second window, assign the DataContext to the object from the main window, and in the main window, when the value changes, raise the INotifyPropertyChanged event to update the visual representation.

S
Space Purr, 2019-12-13
@SpacePurr

Pass the Text from the main window to the constructor of the second window and assign it to the required Label.
For example like this:

public partial class SecondWindow: Window
{
    public SecondWindow(string text)
    {
        InitializeComponent();
        CategoryText.Text = text;
    }
}

If you are using MVVM, then pass the property to the ViewModel of the second window.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question