I have a tab control which has 3 tab pages. Below this tab control on same form/view, i have 3 images controls.
Based on SelectedIndex of tab, i need to change opacity of below 3 images.
As of now i have something like this in SelectionChanged event of Tab control:
switch (Tab.SelectedIndex)
{
case 0:
img1.Opacity= 1;
img2.Opacity = 0.5;
img3.Opacity = 0.5;
break;
case 1:
img1.Opacity = 0.5;
img2.Opacity = 1;
img3.Opacity = 0.5;
break;
case 2:
img1.Opacity = 0.5;
img2.Opacity = 0.5;
img3.Opacity = 1;
break;
}
How do i remove this switch statement? Which design pattern shall i use here ?
I think you can handle this in your xaml itself by using Triggers
.
Also if you want to have this unit testable, you should use MVVM pattern
where you will define properties for SelectedIndex, Opacities
in your ViewModel
and bind them to xaml
You can use the State design pattern explained for instace here. You will define few states and then by condition decide which of them should be used in the moment.
Example:
abstract class State
{
abstract vod Apply(Form context);
}
class StateOne : State
{
override void Apply(Form context)
{
img1.Opacity= 1;
img2.Opacity = 0.5;
img3.Opacity = 0.5;
}
}
You can also combine it with the Factory method design pattern that would decide which state to use.
static class StateFactory
{
static State GetState(condition)
{
if(condition == something)
return new StateOne();
else ...
}
}
This will not remove switch statements from your code, but it will at least be in a reasonable place doing reasonable thing.
Usage:
StateFactory.GetState(condition).Apply(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With