【发布时间】:2016-04-26 06:55:41
【问题描述】:
我想为我的按钮设置单独的突出显示颜色,因此我创建了一个新类“HighlightButton”,它派生自 Button 并仅公开一个附加属性(DP 属性) - SolidColorBrush HighlightColor。
public class HighlightButton : Button {
public SolidColorBrush HighlightColor {
get { return (SolidColorBrush)GetValue(HighlightColorProperty); }
set { SetValue(HighlightColorProperty, value); }
}
// Using a DependencyProperty as the backing store for HighlightColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HighlightColorProperty =
DependencyProperty.Register("HighlightColor", typeof(SolidColorBrush), typeof(HighlightButton), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Color.FromRgb(255,255,255))));
}
-
现在我在 XAML 中使用这个 HighlightButton 而不是 Button:
<con:HighlightButton Style="{StaticResource TransparentButton}"
x:Name="_backButton"
CommandParameter="{Binding PreviousPageViewModel}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType=Window}}"
HighlightColor="Yellow"/>
-
TransparentButton 样式在资源字典中定义:
<Style TargetType="con:HighlightButton" x:Name="_transparentButton" x:Key="TransparentButton">
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="50"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="Transparent">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="{Binding HighlightColor}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="Gray"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如您所见,我希望我的按钮在悬停在按钮上时切换为单独设置的前景色。不幸的是(如您所料)此解决方案不起作用。 WPF 在我的 ViewModel 中查找 Property HightlightColor(TargetType="Button" 对 HighlightColor 一无所知)。可悲的是,当我将 TargetType 更改为我的 HighlightButton 时,整个 Style 崩溃了。
是否有可能实现我正在寻找的东西?我做错了什么?
【问题讨论】:
标签: c# wpf xaml templates styles