Some MVVM frameworks let you raise the PropertyChanged
event by the property itself, not its “string” name. If you’re not using any of them, you may misspell them while typing their names as strings; and also, when you’re using them in more than one place, you’ll have some maintenance problems; e.g., if you rename a property, you have to change it in several places.
Keeping these problems in mind, I came up with this solution. If you think it’s not a good solution or you have better suggestions, they’re really welcomed ;)
- Add your view model class which implements
INotifyPropertyChanged
:
class CustomersViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
- Add a new public method (e.g.,
RaisePropertyChanged
) to centralize the code of raising the PropertyChanged
event:
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
- Add a private class to hold the names of properties inside the View Model class, like this:
private class PropertyNames
{
public static string Id { get { return "Id"; } }
public static string Name { get { return "Name"; } }
public static string Email { get { return "Email"; } }
}
This class is private and cannot be accessed outside of your View Model; and also, you’re not going to create instances of it; that’s why all the properties are declared as static
.
- Now you can add your notifiable properties to the View Model class like this:
private int id;
public int Id
{
get { return this.id; }
set
{
if (this.id == value)
{
return;
}
this.id = value;
RaisePropertyChanged(PropertyNames.Id);
}
}
As you can see, now you’re able to use the public properties of the PropertyNames
class just to return their string names.
So the whole class will look like this:
class CustomersViewModel : INotifyPropertyChanged
{
private int id;
public int Id
{
get { return this.id; }
set
{
if (this.id == value)
{
return;
}
this.id = value;
RaisePropertyChanged(PropertyNames.Id);
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private class PropertyNames
{
public static string Id { get { return "Id"; } }
public static string Name { get { return "Name"; } }
public static string Email { get { return "Email"; } }
}
}
Please write your comments and opinions ;)