Reputation: 69
Building a WPF application in C# I have 5 check boxes and when one or more is selected I want the argument of a it statement to change dynamically. For example, I have Mon, Tue, Wed, Thu & Fri as the check boxes. If user selects Mon, Wed, & Fri then I want the argument for a if statement to change to reflect that. I don't want to make numerous different if statements. Here is a sample I wrote, but the if statement is wrong obviously
string passArg = "";
if(check_mon.IsChecked == true)
{
passArg = "passArg == \"Mon\"";
}
if(passArg)
{
MessageBox.Show("RAN");
}
Sorry if this is a dumb question
Upvotes: 0
Views: 82
Reputation: 7973
You can fire an event when the checkbox is Checked
or Unchecked
and in this method you can set or unset your stuff.
For example in your xaml form:
<CheckBox Checked="Checked" Unchecked="UnChecked"/>
And then create the events:
private void UnChecked(object sender, RoutedEventArgs e) {
//Checked, enable, disable or do whatever you want
}
private void Checked(object sender, RoutedEventArgs e) {
//Checked, enable, disable or do whatever you want
}
Upvotes: 2
Reputation: 152566
Not as simply as you would like. You can generate code dynamically but it's overkill in this case. All you need is:
bool isChecked = false;
if(check_mon.IsChecked && passArg == "Mon")
{
isChecked = true;
}
...
if(isChecked)
{
MessageBox.Show("RAN");
}
I don't want to make numerous different if statements.
Well, you could put the checkboxes in a loop, set the Tag
or some other property and compare that against pasArg
but I tend to go with the simplest solution that works first then focus on making it better. You may find that you spend more time trying to come up with a clever solution (that you may not understand later) when 7 if
statements would work just fine.
Upvotes: 0
Reputation: 99957
You can check for a value in a list:
List<string> checked = new List<string>()
if (check_mon.IsChecked)
{
checked.Add("Mon");
}
if (checked.Contains(passArg))
{
MessageBox.Show("RAN");
}
Upvotes: 1