我正在使用从MenuButton
继承的自定义Button
(没有xaml文件):
public class MenuButton : Button
{
public MenuButton()
{
base.Click += click;
base.MouseLeave += mouseleave;
}
public MenuButton(string caption, ICommand command)
: this()
{
SetValue(ContentProperty, caption);
Caption = caption;
Commando = command;
}
public override void OnApplyTemplate()
{
this.Style = FindResource("MenuButton") as Style;
base.OnApplyTemplate();
}
public ICommand Commando;
public string Caption;
void mouseleave(object sender, MouseEventArgs e)
{
if (selected)
{
SetValue(BackgroundProperty, Brushes.Crimson);
}
else
{
SetValue(BackgroundProperty, Brushes.Transparent);
}
}
bool selected = false;
void click(object sender, RoutedEventArgs e)
{
MenuButtons menu = null;
DependencyObject dep = e.OriginalSource as DependencyObject;
while (dep != null && !(dep is ItemsPresenter))
{
dep = VisualTreeHelper.GetParent(dep);
}
var a = dep as FrameworkElement;
menu = a.DataContext as MenuButtons;
foreach (var item in menu.MenuItems)
{
if (item == sender)
{
SetValue(ForegroundProperty, Brushes.White);
SetValue(BackgroundProperty, Brushes.Crimson);
selected = true;
}
else
{
item.SetValue(ForegroundProperty, Brushes.Black);
item.SetValue(BackgroundProperty, Brushes.Transparent);
item.selected = false;
}
}
Commando.Execute(null);
}
}
}
我应用以下样式:
<Style x:Key="MenuButton"
BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
TargetType="{x:Type c:MenuButton}">
<Setter Property="SnapsToDevicePixels"
Value="True" />
<Setter Property="BorderThickness"
Value="0" />
<Setter Property="DockPanel.Dock"
Value="Left" />
<Setter Property="Margin"
Value="0" />
<Setter Property="Padding"
Value="8" />
<Setter Property="FontSize"
Value="11" />
<Setter Property="FontFamily"
Value="Verdana" />
</Style>
这很有效,ToolBar.ButtonStyleKey提供了漂亮的蓝色/灰色悬停颜色。
在后面的代码中,我想根据每个按钮“选中”状态设置前景色和背景色。在事件void click(object sender, RoutedEventArgs e)
中,我为数组中的所有菜单项设置了这些颜色(它们在用户控件中分组)。
foreach (var item in menu.MenuItems)
{
if (item == sender)
{
SetValue(ForegroundProperty, Brushes.White);
SetValue(BackgroundProperty, Brushes.Crimson);
selected = true;
}
else
{
item.SetValue(ForegroundProperty, Brushes.Black);
item.SetValue(BackgroundProperty, Brushes.Transparent);
item.selected = false;
}
}
现在前景色变好了。但背景颜色可能会被ToolBar.ButtonStyleKey
覆盖,并保持蓝色/灰色!只有当我点击另一个 MenuButton
时,深红色才出现在我刚刚离开按钮上。奇怪的是我无法正确设置背景,我怎么能解决这个问题,而不用编写恶魔般的ControlTemplates?