鼠标在WPF中离开时的默认按钮颜色



当鼠标通过事件中的发送器输入多个按钮时,我正在尝试更改这些按钮的颜色。

它工作得很好,但我想知道当鼠标离开的事件被触发时,如果它存在,而不是通过六进制代码或类似的东西来改变颜色,如果;默认颜色按钮";方法可能存在吗?

实际上,当鼠标覆盖任何按钮时(我的按钮是椭圆(:

private void ButtonsOvering_MouseEnter(object sender, MouseEventArgs e)
{
(sender as Ellipse).Fill = Brushes.IndianRed;
}

当鼠标离开任何按钮时:

private void ButtonsLeaving_MouseLeave(object sender, MouseEventArgs e)
{
Color yoloColor = new Color();
yoloColor = (Color)ColorConverter.ConvertFromString("#FF252424");
SolidColorBrush namasteColor = new SolidColorBrush(yoloColor);
(sender as Ellipse).Fill = namasteColor;
}

#FF252424是我为大多数按钮提供的默认颜色,所以在这种情况下,当把按钮留给我的鼠标时,按钮的颜色将与我的鼠标没有覆盖它时的颜色相同。

但是,因为我有其他按钮使用了我给它们的另一种默认颜色,所以当我的鼠标离开按钮时,我不想创建更多的代码行来告诉用另一个HexCode更改颜色。

WPF中是否存在类似Default.Color.Button的方法?

Thx

当然没有这样的方法。您可以在鼠标上更改之前存储原始颜色:

private Dictionary<Shape, Brush> ShapeDefaultBrushMap { get; }
private void ButtonsOvering_MouseEnter(object sender, MouseEventArgs e)
{
var shape = sender as Shape;
this.ShapeDefaultBrushMap[shape] = shape.Fill;
shape.Fill = Brushes.IndianRed;
}
private void ButtonsLeaving_MouseLeave(object sender, MouseEventArgs e)
{
var shape = sender as Shape;
if (this.ShapeDefaultBrushMap.TryGetValue(shape, out Brush shapeDefaultBrush))
{
shape.Fill = shapeDefaultBrush;
}
}

首先,您应该使用Button控件,该控件内置了所有必要的按钮功能。但是,如果您试图获得具有自定义形状的按钮,则需要覆盖按钮的默认模板。有关详细信息,请查看本指南。

关于您对椭圆的默认颜色的担忧,当鼠标悬停在椭圆上时,椭圆会发生变化,这里最好的方法是使用样式

以下是如何为您的案例做到这一点:

<!--
In App.xaml inside <Application.Resources>...</Application.Resources>
or in MainWindow.xaml inside <Window.Resources>...</Window.Resources>
-->
<Style x:Key="EllipseStyle1" TargetType="Ellipse">
<Setter Property="Fill" Value="#FF252424"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="IndianRed"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="EllipseStyle2" TargetType="Ellipse">
<!-- Replace 'Green' with your other default colors -->
<Setter Property="Fill" Value="Green"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="IndianRed"/>
</Trigger>
</Style.Triggers>
</Style>
...
<!-- Use it as following -->
<Ellipse Style="{StaticResource EllipseStyle1}"/>

好处:由于您正在寻找一种方法来告诉椭圆,在鼠标离开事件处理程序中,将其Fill颜色更改回默认,因此在WPF中有一种方法可以做到这一点,但您必须应用一种定义缺省颜色的样式(类似于上述样式,但没有<Style.Triggers>...</Style.Triggers>(,否则系统默认值将应用于此。该方法称为ClearValue,可用于以下用途:

private void ButtonsLeaving_MouseLeave(object sender, MouseEventArgs e)
{
// This will make the ellipse without color if there is
// no style applied with custom value for Fill property
(sender as Ellipse).ClearValue(Ellipse.FillProperty);
}

最新更新