Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access WPF user control value

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

like image 333
parag Avatar asked May 03 '10 10:05

parag


2 Answers

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";
}
like image 99
Tiberiu Ana Avatar answered Nov 14 '22 12:11

Tiberiu Ana


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.

like image 2
slugster Avatar answered Nov 14 '22 13:11

slugster