Search code examples
c#wpfmvvmuser-controls

how do UserControls get access to a textbox's value in MainWindow?


The UserControls are put into MainWindow but they don't instantiate each other - they don't have owner-member relationship.

I need the back-end code of UserControls to be able to get the value from a TextBox of MainWindow. I have been told to use data binding but I don't really know what to be bound in UserControls.

Create an interface:

interface Interface_ProSimIP
{
    string ProSimIP_Text { get; set; }
}

In MainWindow ViewModel:

    string Interface_ProSimIP.ProSimIP_Text
    {
        get
        {
            return ProSimIP.Text;
        }
        set
        {  
        }
    }

In MainWindow View:

<TextBox x:Name="ProSimIP" Text="{Binding Path=ProSimIP_Text, Mode=OneWay}..."

I don't know am I right to do it this way and I don't know how to implement the interface in UserControls code behind.


Solution

  • You could use the same DataContext (view model) for the parent window and the user controls. Set the DataContext property of the window to an instance of a view model class where you implement your logic and then bind to properties of the view model from the XAML views of the window and the user controls. Then the window and the controls effectively share the same "back-end" code.

    This pattern is known as MVVM and it's the recommended pattern to use when developing XAML based UI applications. You should learn it. The following MSDN page might be provide a good starting point for you: https://msdn.microsoft.com/en-us/library/hh848246.aspx.

    Another (worse but maybe faster to adopt if you don't know anything about nor follow the MVVM pattern) approach would be to get a reference to the window from the UserControl using the Window.GetWindow method, and then access any control that's defined in the window directly:

    var window = Window.GetWindow(this) as MainWindow:
    if (window != null)
        string text = window.ProSimIP.Text;
    

    You should note that this kind of code doesn't follow follow best practices when it comes to developing loosely coupled, maintainable and testable applications though.