2016-04-26 38 views
0

我想爲我的按鈕設置單獨的突出顯示顏色,所以我創建了一個新的類「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時,整個樣式崩潰。

它甚至有可能實現我在找什麼?我究竟做錯了什麼?

回答

1

我的模板

<ControlTemplate TargetType="con:HighlightButton"> 

設定具體的目標類型和修訂後的BTW結合這樣

<Setter Property="Foreground" Value="{Binding HighlightColor, RelativeSource={RelativeSource Self}}"/> 

,前景和HighlightColor都是白色的默認。沒有有或沒有觸發任何明顯的差異(會有,如果<Setter Property="Foreground" Value="White"/>設置一些其他顏色,例如)

還我寧願用Brush類型的屬性,以允許不同類型的畫筆

+0

那做了訣竅 - 我總是忘記自我約束。謝謝 :) – C4p741nZ

相關問題