简体   繁体   中英

Get Text of Custom Dialog (UserControl) from Parent UserControl

I have a UserControl as Parent and i am opening a custom dialog (user control) as shown in the code below:

        Window dialog = new Window
        {
            Title = "A Dialog Box",
            Content = new UserControlDialog(),
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.NoResize
        };
        dialog.ShowDialog();

How can i get the text from the textbox inside the UserControl Dialog?

First, create a public property in your UserControlDialog control, let's say named Value . When the user does something in the dialog, set the value from the TextBox to the Value property:

Value = SomeTextBox.Text;

When the dialog window is closed, simply read the value from the dialog control:

...
dialog.ShowDialog();
string result = dialog.Value;

A better solution would be to data bind the Value property to the inner TextBox control, but to do this, you'd either need to implement the INotifyPropertyChanged Interface , or create the Value property as a DependencyProperty :

Inside the UserControlDialog control:

<TextBox Text="{Binding Value, RelativeSource={RelativeSource 
    FindAncestor={x:Type YourLocalPrefix:UserControlDialog}}}" ... />

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