Search code examples
c#wpfxamlmvvmuser-controls

where to put the textbox that for different UserControls to use?


In my WPF program. I have a DataModel.cs, MainWindow.xaml & MainWindow.xaml.cs and many UserControl.xaml & UserControl.xaml.cs which are integrated into MainWindow.xaml in this way:

    <Border...>
        <UserControl1/>
    </Border>
    <Border...>
        <UserControl2/>
    </Border>
    ...

I am not sure if it can be called MVVM?

Some of my UserControl.xaml.cs need to use the same string for connection which should be typed on the UI textbox somewhere like this:

DataModel.connection.Connect("[textbox.text]");

My question is where do I put this textbox so that each UserControl can get access to it and how? Thanks.


Solution

  • You create a string property in your DataModel class:

    public class DataModel : INotifyPropertyChanged
    {
        private string _text;
        public string Name
        {
            get { return _text; }
            set
            {
                _text = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string property)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
        }
    }
    

    ...and bind the TextBox in the view to this string property:

    <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
    

    Provided that you set the DataContext of the window to an instance of your DataModel class:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new DataModel();
        }
    }
    

    ...the source property (Text) will be updated whenever you type something into the TextBox. If you let the UserControls inherit the DataContext from the parent window, i.e. don't set the DataContext of the UserControls explicitly somewhere, they can bind to the very same Text property and get the latest value "automatically" as the DataModel implement the INotifyPropertyChanged interface and raise the PropertyChanged event.

    This is roughly how basic MVVM works.