Since MvvmLight exposes it’s own ViewModelBase you cannot use this little script to raise the INotifyPropertyChangedEventHandler, because .NET doesn’t allow you to raise events in derived classes. This is because the compiler generates a private delegate (it’s in VB.NET but that doesn’t matter).
And since the ViewModelBase only exposes a protected RaiseProperty(string propertyName) I cannot use strongly typed reflection.
So I found some code, and rewrote it like this.
Now you can create a class that inherits from ViewModelBase, and make your ViewModels inherit from your just created class.
Now you have a pattern like this:
ViewModelBase <—DefaultViewModel <—MainPageViewModel
And your DefaultViewModel should look like this:
- public abstract class DefaultViewModel : ViewModelBase
- {
- protected void RaisePropertyChanged<TValue>(Expression<Func<TValue>> propertySelector)
- {
- var memberExpression = (propertySelector.Body as MemberExpression);
- if (null != memberExpression)
- this.RaisePropertyChanged(memberExpression.Member.Name);
- }
- }
And your MainPageViewModel (for example):
- public class MainPageViewModel : DefaultViewModel
- {
- private decimal _remainingCredits;
- /// <summary>
- /// Remaining credits of the current account
- /// </summary>
- public decimal RemainingCredits
- {
- get
- {
- return this._remainingCredits;
- }
- set
- {
- if (this._remainingCredits != value)
- {
- this._remainingCredits = value;
- this.RaisePropertyChanged(() => RemainingCredits);
- }
- }
- }
- }
You can use the form of RaisePropertyChanged(() => NameOfProperty);
This way, when you rename a variable in your code the refactor engine picks it up and renames it accordingly. (it forget strings
Good luck,
Kristof