Studying the pattern, I learned how to more less associate window elements with ViewModel properties, that is, classes, as I understand it, as intermediaries between code / logic and a window. However, when looking for how code / logic to interact with the ViewModel failed. When independent attempts at binding came to the same thing - there is no single control center. It seems the whole point is that there is no single center, but I absolutely do not understand how to implement such a logic. I tried to look for examples, but they all manipulate some prohibitively complex for a beginner C # features. Please explain how I, for example, make an authorization window and go to some kind of hall / homepage.
This will be the code zaml:
<StackPanel> <TextBox FontSize="20" Text="{Binding Login, Mode=TwoWay}"/> <TextBox FontSize="20" Text="{Binding Pass, Mode=TwoWay}"/> <Button Height="30" Click="Button_Click"/> </StackPanel> With # window code:
public partial class MainWindow : Window { ViewModel ViewModel = new ViewModel(); public MainWindow() { InitializeComponent(); DataContext = ViewModel; } private void Button_Click(object sender, RoutedEventArgs e) { ViewModel.Login = "1111"; ViewModel.Pass = "2222"; } } ViewModel Code:
class ViewModel : INotifyPropertyChanged { private string login; private string pass; public string Login { get { return login; } set { login = value; OnPropertyChanged("Login"); } } public string Pass { get { return pass; } set { pass = value; OnPropertyChanged("Pass"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } I hope you do not go blind
As you can see, the only way to bind the ViewModel I own is to specify it in code using a DataContext. At the same time, an object is created which is not monitored anywhere. Not to mention the fact that to organize the interaction of all data among themselves. In this example, the logic is placed in the click method, since I cannot imagine how the logic written in a separate file can be linked here without crutches.
{Binding Login, Mode=TwoWay}, then this isViewModel.Login = "1111";in kodbihind do not need. Download and see an example . - BulsonRelayCommandclass from this exampleRelayCommandIt will be useful to you in the implementation of commands in your own projects. - Bulson