MVVM (Model-View-ViewModel) Kalıbı Winforms
model
public class Person
{
public string FirstName {get; set;}
public string LastName {get; set;}
}
ViewModel
public class PersonViewModel : INotifyPropertyChanged
{
private Person _Model;
public string FirstName
{
get { return _Model.FirstName; }
set(string value)
{
_Model.FirstName = value;
this.NotifyPropertyChanged("FirstName");
this.NotifyPropertyChanged("FullName"); //Inform View about value changed
}
}
public string LastName
{
get { return _Model.LastName; }
set(string value)
{
_Model.LastName = value;
this.NotifyPropertyChanged("LastName");
this.NotifyPropertyChanged("FullName");
}
}
//ViewModel can contain property which serves view
//For example: FullName not necessary in the Model
public String FullName
{
get { return _Model.FirstName + " " + _Model.LastName; }
}
//Implementing INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
Görünüm
public class PersonView: Form
{
//Add two textbox and one label to the form
//Add BindingSource control which will handle
//ViewModel and Views controls changes
//As viewmodel you can use any type which of course have same named properties
public PersonView(Object viewmodel)
{
this.InitializeComponents();
this.ViewModelBindingSource.DataSource = viewmodel;
this.InitializeDataBindings();
}
private void InitializeDataBindings()
{
this.TextBoxFirstName.DataBindings.Add("Text", this.ViewModelBindingSource, "FirstName", true);
this.TextBoxLastName.DataBindings.Add("Text", this.ViewModelBindingSource, "LastName", true);
this.LabelFullName.DataBindings.Add("Text", this.ViewModelBindingSource, "FullName", true);
}
}
MSDN'den Winforms'da veri bağlama hakkında daha fazla bilgi edinin