I am developing wpf application. I am having the instance of Color object in C#. Suppose I have instance of red Color object i.e. Color c = Color.FromArgb(255,255,0,0)
Now suppose that I have one value which ranges from 1 to 10. So based on this value I want to change the color of the 'c' object. I want light red for 1 and dark red for 10. The light red becomes the dark as the value increases from 1. How can I do this in C# for wpf application ? Can you please provide me any code or link through which I can resolve the above issue ?
A cleaner solution would be to juxtapose 2 rectangles: one is the color you want, the other is black.
Then play with Opacity
on the black rectangle to darken/lighten the underlying color.
It would look like:
<Grid>
<Rectangle Fill="{Binding myColor}" />
<Rectangle Fill="Black" Opacity="{Binding colorModifierPercentage}" />
</Grid>
Of course, colorModifierPercentage
must be a number between 0 and 1, and rectangle can be any Shape.
You can try to simply multiply red, green and blue components by some coefficient.
public static Color ChangeLightness(this Color color, float coef)
{
return Color.FromArgb((int)(color.R * coef), (int)(color.G * coef),
(int)(color.B * coef));
}
Or, if you'd like to use an integer value from 1 to 10 instead of the coefficient:
private const int MinLightness = 1;
private const int MaxLightness = 10;
private const float MinLightnessCoef = 1f;
private const float MaxLightnessCoef = 0.4f;
public static Color ChangeLightness(this Color color, int lightness)
{
if (lightness < MinLightness)
lightness = MinLightness;
else if (lightness > MaxLightness)
lightness = MaxLightness;
float coef = MinLightnessCoef +
(
(lightness - MinLightness) *
((MaxLightnessCoef - MinLightnessCoef) / (MaxLightness - MinLightness))
);
return Color.FromArgb(color.A, (int)(color.R * coef), (int)(color.G * coef),
(int)(color.B * coef));
}
What about a Style DataTrigger, if you have a set number of values?
https://www.google.co.uk/search?q=c%23+wpf+style+datatrigger
<Button>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding NameOfYourProperty}" Value="0">
<Setter Property="Background"
Value="#FF000000" />
</DataTrigger>
<DataTrigger Binding="{Binding NameOfYourProperty}" Value="1">
<Setter Property="Background"
Value="#FF110000" />
</DataTrigger>
<DataTrigger Binding="{Binding NameOfYourProperty}" Value="2">
<Setter Property="Background"
Value="#FF220000" />
</DataTrigger>
( etc ... )
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Then if you need to reuse the style then you could put in the <Resources>
section of your window/usercontrol.
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