kkh
kkh

Reputation: 4869

Interaction between user controls

I have 2 usercontrols in a wpf application. In my user control A, when I click on a button it will grab the text inside a textbox from usercontrol B. How do I access the text in the textbox when i click on the button in A?

  public partial class UserControlB : UserControl
  {
      public string TextBoxText { get { return this.TextBoxB.Text; } }
  }

Then in usercontrol A, when i click the button

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        String s = UserControlB.TextBoxText ;

    }

Upvotes: 1

Views: 2026

Answers (4)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

In your question you aren't correctly referencing your UserControlB

private void button1_Click(object sender, RoutedEventArgs e)     
{
    String s = UserControlB.TextBoxText ;      
}

Here you are looking at the class called UserControlB, not an object or an instance of UserControlB. In other words, you're not specifying which UserControlB you want to look at. If you had five UserControlB on your screen, how does the button know which one to use?

Read Classes and Objects to learn about the difference between Classes (like UserControlB) and Objects (items that you can reference and use in your program).

The UserControlB that you have on your page or view should have a Name if you want to use it. Once you find the name, you can reference it like this:

// inside the control which contains your UserControlB
public MainPage()
{
    // find it according to its Name property
    UserControlB theOneIWantToUse = this.UserControlB_1;

    // once you identify it, you can get the Text value from it
    String s = theOneIWantToUse.Text;
}

Upvotes: 0

Chinmoy
Chinmoy

Reputation: 1754

You can try this:

In UserControl A,

private void button1_Click(object sender, RoutedEventArgs e) {

   MainWindow rootWindow = Application.Current.MainWindow as MainWindow;
   String s = (String)rootWindow.B.TextBoxB.text;

}

Upvotes: 0

c8irish
c8irish

Reputation: 155

I know this is a short answer, but i would think that a FindControl("textboxName') should work.

string text = userControlB.FindControl("textbox")

Upvotes: 0

ojlovecd
ojlovecd

Reputation: 4902

Add a property in B, returning the text of the TextBox:

public class UserControlB
{
    public string TextBoxText { get { return this.TextBox1.Text; } }
}

Find the instance of the UserControl B in your xaml, then call the property as follows:

string txt = this.UserControlB.TextBoxText;

Upvotes: 2

Related Questions