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.
Any help appreciated :-)
You could avoid exeucting the command and just call your method from each setter, e.g.:
private bool _port1;
public bool Port1
{
get { return _port1; }
set { _port1 = value; SetPort(); }
}
If the SetPort
modifies the other properties, you could use a flag to determine whether it should be invoked:
private bool _setPort = true;
private bool _port1;
public bool Port1
{
get { return _port1; }
set
{
_port1 = value;
if (_setPort)
{
_setPort = false;
SetPort();
_setPort = true;
}
}
}
You could do the same thing in the Execute
method of your command if you still want to use a command for some reason.
The _setPort
field 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 PropertyChanged
event:
_port2 = true;
OnPropertyChanged(nameof(Port2));
This will bypass the setter and avoid calling the method.