I have 2 text box in WPF user control and button on WPF form. How can I access those textbox value on the button click event of that main form where I am using the WPF user control
First of all, keep in mind that WPF is not WinForms -- in theory you should data bind your TextBoxes to properties and then change the value of the properties, instead of accessing the TextBoxes directly!
That being said, all you have to do is to name the UserControl and the TextBoxes, and then access them, like this:
Int MyUserControl.xaml:
<TextBox x:Name="myTextBox1"/>
<TextBox x:Name="myTextBox2"/>
In MyWindow.xaml:
<local:MyUserControl x:Name="myUserControlInstance"/>
<Button Content="Click me" Click="Button_Click" />
In MyWindow.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e) {
myUserControlInstance.myTextBox1.Text = "Foo";
myUserControlInstance.myTextBox2.Text = "Bar";
}
In the usercontrol, make two public properties which return a string:
public property Textbox1Text
{
get { return TextBox1.Text; }
}
then the text from the textbox controls is visible to the main form.
Or a better option: have an event that the usercontrol can raise, call it something like TextChanged
. Of course you want a better name for it than that, so let's just pretend that your first textbox is designed for the user to enter a name and call the event NameTextChanged
, then your event will be something like this:
public MainWindow()
{
InitializeComponent();
TextBox1.TextChanged += new TextChangedEventHandler(TextBox1_TextChanged);
}
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (NameTextChanged!= null)
this.NameTextChanged(this, e);
}
public event TextChangedEventHandler NameTextChanged;
or better yet, you could go for a routed event - but stick with the basics first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With