Reputation: 138
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.
Upvotes: 0
Views: 42
Reputation: 169340
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.
Upvotes: 1
Reputation: 145
I think you need read more on MVVM, short answer, as long as you are not referencing and UI elements directly in you ViewModel, you can consider it MVVM.
There are multiple ways you can do it, I would define and interface with
public interface IProvideTextProperty {string SomeText{get;set;}}
Implement this interface in all UserControls that use this property
Upvotes: 0