简体   繁体   中英

How to pass a string from user control to its parent Window in WPF?

I have custom made UserControl with textbox and button. I add this UC to main window and now I want that when I click on button inside UC, text from UC textbox gets transfered into textbox or label in main window. If I'm correct I should made custom event and bind it somewhere or something like that but I can't find anything usefull so I would be glad for some help or a good tutorial.

You could easily achieve what you need by using a property in the UC and subscribe to the propertychanged event of this property in the MainWindow.

In UserControl

public class UserControl : BindableBase
{

    private string textboxText;
    public string TextBoxText
    {
       get { return textboxText; }
       set { SetProperty(ref textboxText,value); }
    }

}

Thus when the textbox lose focus, the property textboxText is updated.

In MainWindow

public class MainWindow
{
    public UserControl UserControlInstance = new UserControl();
    public string textPropertyMainWindow;
    public MainWindow()
    {
       UserControlInstance.TextBoxText.PropertyChanged += PropertyChangedHandler;
    }

    private void PropertyChangedHandler(object obj)
    {
       textPropertyMainWindow = UserControlInstance.TextBoxText;
    }
}

Hope you got the point. Revert if any further help needed.

The simplest way must be this and you'd better to practice because this can be used many times basically.

Declare a datatype in the field of class like,

string textwhichuserinputed;

And assign a value to the variable in Event or Method(wherever) like,

textwhichuserinputed= UCtextBox.Text;

After the assignment, the value of the variable will be set as UCtextBox.Text. And before the assignment the value is null.

Then, afterward, you can use textwhichuserinputed everywhere in the class.

This is simplest and most basic way you'd better to practice.
And this is called Global Variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM