-
Notifications
You must be signed in to change notification settings - Fork 0
ViewModel: Getting started with data binding
Data binding - or to be more precise the MVVM pattern (Model-View-ViewModel) - is an essential part in developing robust and scalable UI applications with WPF. To aleviate the setup of viewmodels and bindable collections this library offers some base classes from which you can extend.
In the following topics we're going to setup a basic viewmodel with properties inside.
Setting up a new viewmodel is pretty easy. All we have to do is extend a class with the "ViewModelBase" class:
public class MainViewModel : ViewModelBase
{
}After this we create our bindable properties. For each property we want to bind we need both a class variable and a public property. Inside the set function of our property we call the method "InvokePropertyChanged()" from ViewModelBase. This in turn prompts WPF to update bindings to properties with the property name.
public class MainViewModel : ViewModelBase
{
private string mName;
private int mAge;
private DateTime mBirthday;
public string Name
{
get => mName;
set
{
mName = value;
InvokePropertyChanged();
}
}
public int Age
{
get => mAge;
set
{
mAge = value;
InvokePropertyChanged();
}
}
public DateTime Birthday
{
get => mBirthday;
set
{
mBirthday = value;
InvokePropertyChanged();
}
}
}Please note that "InvokePropertyChanged()" can be called from anywhere inside the class, but you need to provide the name of the property you're trying to update. The reason why we can omit the name inside a property is because the method will fill in the name for us. For example, if we want to update all of our properties with a method, we would do it like this:
public class MainViewModel : ViewModelBase
{
public string Name { ... }
public int Age { ... }
public DateTime Birthday { ... }
public void RefreshBindings()
{
InvokePropertyChanged("Name");
InvokePropertyChanged("Age");
InvokePropertyChanged("Birthday");
}
}Next up: Observing classes
-
Home
- Tasty.Logging
-
Tasty.SQLiteManager
- SQLiteManager 2.0 and up:
- SQLiteManager 1.0.3 and below:
- Tasty.ViewModel