How do you handle 'SelectedItemChanged' events in a MVVM ViewModel?
- by Travis
I have some logic that depends upon two properties being set, as it executes when both properties have a value. For example:
private void DoCalc() {
if (string.IsNullOrEmpty(Property1) || string.IsNullOrEmpty(Property2))
return;
Property3 = Property1 + " " + Property2;
}
That code would need to be executed every time Property1 or Property2 changed, but I'm having trouble figuring out how to do it in a stylistically acceptable manner. Here are the choices as I see them:
1) Call method from ViewModel
I don't have a problem with this conceptually, as the logic is still in the ViewModel - I'm not a 'No code-behind' nazi. However, the 'trigger' logic (when either property changes) is still in the UI layer, which I don't love. The codebehind would look like this:
void ComboBox_Property1_SelectedItemChanged(object sender, RoutedEventArgs e) {
viewModel.DoCalc();
}
2) Call method from Property Setter
This approach seems the most 'pure', but it also seems ugly, as if the logic is hidden. It would look like this:
public string Property1 {
get {return property1;}
set {
if (property1 != value) {
property1 = value;
NotifyPropertyChanged("Property1");
DoCalc();
}
}
}
3) Hook into the PropertyChanged event
I'm now thinking this might be the right approach, but it feels weird to hook into the property changed event in the implementing viewmodel. It would look something like this:
public ViewModel() {
this.PropertyChanged += new PropertyChangedEventHandler(ViewModel_PropertyChanged);
}
void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == "Property1" || e.PropertyName == "Property2") {
DoCalc();
}
}
So, my question is, if you were browsing through some source code with that requirement, which approach would you prefer to see implemented (and why?). Thanks for any input.