P
P
postya2019-12-09 12:44:20
WPF
postya, 2019-12-09 12:44:20

How to replace the if else construct with a switch?

There are several buttons, when you click on each, changes occur with other elements.
Here I wrote the code for 2 buttons, and there will be 8 of them in total.
I used the if else states. Everything works, but everything is quite cumbersome
How can I use switch instead of if else to be more compact in the code?
CategoryToggle1 - buttons
RectCategory1 - rectangle

if (CategoryToggle1.IsChecked == true)
                {
                    RectCategory1.Fill = new SolidColorBrush(dialog.Color);

                    Properties.Settings.Default.RectangleCategory1 = new BrushConverter().ConvertToString(dialog.Color);

                }
                else if (CategoryToggle2.IsChecked == true)
                {
                    RectCategory2.Fill = new SolidColorBrush(dialog.Color);

                    Properties.Settings.Default.RectangleCategory2 = new BrushConverter().ConvertToString(dialog.Color);
                }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2019-12-09
@postya

But with switchwill not be more compact.
It will be more compact if you place your own CategoryTogglein RectangleCategoryarrays. And then you will have only one logic, check the checker and apply the brush.

for (int i = 0; i < categoryToggleArr.Length; i++)
{
   if (categoryToggleArr[i].IsChecked)
   {
      RectCategoryArr[i].Fill = new SolidColorBrush(dialog.Color);
      RectangleCategoryArr[i] = new BrushConverter().ConvertToString(dialog.Color);
   }
}

V
Vladimir Korotenko, 2019-12-09
@firedragon

switch works on one variable.
you have 2
CategoryToggle1.IsChecked
CategoryToggle2.IsChecked

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question