我想爲我的按鈕設置單獨的突出顯示顏色,所以我創建了一個新的類「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))));
}
-
現在我用這個HighlightButton代替按鈕我的XAML中:
<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的屬性HightlightColor(TargetType =「Button」不知道任何關於HighlightColor的內容)。可悲的是,當我將TargetType更改爲我的HighlightButton時,整個樣式崩潰。
它甚至有可能實現我在找什麼?我究竟做錯了什麼?
那做了訣竅 - 我總是忘記自我約束。謝謝 :) – C4p741nZ