C
C#•6mo ago
Ice_

WPF Checkbox handling

I have a class(Owner) which has a property list of a second class(Pet) and vice versa (many to many relationship). It is all connected with a dbcontext. I am supposed to check checkboxes of pets that a specific owner has. This works and it's storing everything in the database. The problem I have is when I select an owner, I want to iterate through all the pets for that particular owner and automatically check all the checkboxes for those pets in the list showing. If I check/uncheck a box through code, the IsChecked on each checkbox (which is bound to a bool property) is triggered and it sets the bool to true or false depending on the currently value (if checked = uncheck and the other way around). This in turn also triggers an add or remove to the list/database which is not what I want since the user never clicked the checkboxes. I know there is Checked and Unchecked events for checkboxes but I'm supposed to leave the MainWindow.xaml file as empty as possible as it's a part of my assignment. When using Command it seems like you can't add parameters either. Any tips/ideas? Going to try to tackle this tomorrow with a friend!
4 Replies
Honza K.
Honza K.•6mo ago
basically, you will bind the Checked property to a viewmodel's boolean property from the view (xaml) and handle the check/uncheck in the viewmodel class also be careful about checking/unchecking directly accessing/changing/querying the DB... user's are crazy and will click the little checkbox like 10 times just because they are bored and don't know what to do next 😄
Ice_
Ice_•6mo ago
That is what I have done. The problem is the check/uncheck handling And I rather not create events for Check or Uncheck in the main xaml file
Honza K.
Honza K.•6mo ago
did you do two way binding in xaml? you have to do this IsChecked="{Binding InstallUnderLocalMachine, Mode=TwoWay}" and then in the viewmodel you handle whatever you need in the setter, eg. raising an event that this value changed (OnPropertyChanged) or you custom logic to handle what you need
public bool InstallUnderLocalMachine
{
get { return installUnderLocalMachine; }
set
{
installUnderLocalMachine = value;
if (value == true && adminRights == true)
storeLocation = StoreLocation.LocalMachine;
else if (value == true && adminRights == false)
{
runAsAdmin();
}
else
storeLocation = StoreLocation.CurrentUser;
}
}
public bool InstallUnderLocalMachine
{
get { return installUnderLocalMachine; }
set
{
installUnderLocalMachine = value;
if (value == true && adminRights == true)
storeLocation = StoreLocation.LocalMachine;
else if (value == true && adminRights == false)
{
runAsAdmin();
}
else
storeLocation = StoreLocation.CurrentUser;
}
}
in this example I dont need the UI to react to changes from code, because changing this property basically means restarting the application... so everything you need to handle regarding the (un)checked event is done in the property's setter in the viewmodel