I have some logic that depends on whether two properties are set, since it runs when both properties have a value. For instance:
private void DoCalc() { if (string.IsNullOrEmpty(Property1) || string.IsNullOrEmpty(Property2)) return; Property3 = Property1 + " " + Property2; }
This code will need to be executed each time Property1 or Property2 changes, but itโs hard for me to figure out how to do this in a stylistically acceptable way. Here is the choice I see:
1) Method call from ViewModel
I have no problem with this conceptually, since the logic is still in the ViewModel - I am not "without code" Nazis. However, the trigger logic (when property changes) is still in the user interface layer, which I don't like. Codebehind will look like this:
void ComboBox_Property1_SelectedItemChanged(object sender, RoutedEventArgs e) { viewModel.DoCalc(); }
2) Method call from Property Setter
This approach seems the most โcleanโ, but it also seems ugly, as if logic is hidden. It will look like this:
public string Property1 { get {return property1;} set { if (property1 != value) { property1 = value; NotifyPropertyChanged("Property1"); DoCalc(); } } }
3) Connect to the PropertyChanged event
Now I think that this may be the right approach, but it is strange to connect to an event modified by properties in an implementing viewmodel. It will 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 looking at some source code with this requirement, which approach would you rather see implemented (and why?). Thanks for any input.