Darken element color
I want to chang开发者_JS百科e the background color of an element when the mouseEnter event fires. How to make the color of the background darker?? I thought I can use an opacity mask, but it's a gradient, but I need it to be solid. Also it has to be in visual basic code, not in xaml. Please help me!
The opacity mask is not a very good option as it modifies the opacity. Also, the opacitymask can be any kind of brush it doesn't have to be a gradient.
You could do one of two things: manipulate the current brush or add a black rectangle on top of the control and change the opacity of the rectangle.
If you let me know what you prefer I could write some code.
(Why does it have to be code and not xaml?)
EDIT
<Window x:Class="TestWpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpfApplication"
Title="MainWindow"
Height="350"
Width="525">
<StackPanel>
<Grid>
<TextBox Background="Red"
FontSize="24" />
<Rectangle x:Name="overlay"
Fill="Black"
IsHitTestVisible="False"
Opacity="0" />
<Grid.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="0.9"
Duration="0:0:0.2"
Storyboard.TargetName="overlay"
Storyboard.TargetProperty="(Rectangle.Opacity)" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="0"
Duration="0:0:0.2"
Storyboard.TargetName="overlay"
Storyboard.TargetProperty="(Rectangle.Opacity)" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
</Grid>
</StackPanel>
</Window>
I would probably use a ValueConverter
for this. Recently used this converter to change opacity:
public class ChangeColorOpacityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Color input = (Color)value;
input.A = byte.Parse((string)parameter); //Changes alpha to ValueConverterParameter
return input;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
You could change this to darken the color, just divide all colour channels by two for example.
VC usage example:
<Border>
<Border.Resources>
<vc:DarkenColorConverter x:Key="DarkenColorConverter"/>
</Border.Resources>
<Border.Background>
<SolidColorBrush Color="{Binding MyColor, Converter={StaticResource DarkenColorConverter}}"/>
</Border.Background>
</Border>
If you make use of the parameter you need to specify the value in the binding as ConverterParameter
.
精彩评论