In my View I have 8 checkboxes all bound to a different property in the Model, lets say bool port1 ... port8. The property changes when the concerned checkbox is clicked.
When the user checks or unchecks one of these checkboxes, I also execute a binded command 'SetPortCommand'. The command executes a function like SetPort(uint numPort, bool set)
My view looks like this:
<CheckBox x:Name="cbPort1" Content="port1" Command="{Binding SetPortCommand}">
<CheckBox.IsChecked>
<Binding Path="MyModel.Port1"/>
</CheckBox.IsChecked>
</CheckBox>
Behind the whole thing is quite slow hardware, so I would like to avoid calling the function SetPort() for each port. I could use 8 commands like SetPortCommand1 to SetPortCommand8, but that causes lots of duplicate code.
I had the following ideas, but I do not know how to implement it, neither which one wouldf be conform to MVVM.
- idea would be to somehow pass a constant to the command, telling it which of the 8 ports it should check or uncheck. Is there a easy way to do this?
- idea would be to somehow use the OnPropertyChanged()-Event to call the function in here.
Any help appreciated :-)
You could avoid exeucting the command and just call your method from each setter, e.g.:
If the
SetPortmodifies the other properties, you could use a flag to determine whether it should be invoked:You could do the same thing in the
Executemethod of your command if you still want to use a command for some reason.The
_setPortfield prevents the method from getting called for each source property.Alternatively, you could also avoid setting the property in the method and instead set the backing field and raise the
PropertyChangedevent: _port2 = true; OnPropertyChanged(nameof(Port2));This will bypass the setter and avoid calling the method.