[英]Bind Button Template Foreground to property of class which derives from Button
我想為按鈕設置單獨的突出顯示顏色,所以我創建了一個新類“ 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"/>
--
透明按鈕樣式在資源字典中定義:
<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時,整個樣式都會崩潰。
甚至有可能達到我的期望? 我究竟做錯了什么?
我為模板設置了具體的目標類型
<ControlTemplate TargetType="con:HighlightButton">
並像這樣修改綁定
<Setter Property="Foreground" Value="{Binding HighlightColor, RelativeSource={RelativeSource Self}}"/>
順便說一句,默認情況下,Foreground和HighlightColor均為白色。 有或沒有觸發器都沒有任何可見的區別(例如,將<Setter Property="Foreground" Value="White"/>
設置為其他顏色)
我也更喜歡使用Brush
類型的屬性來允許不同類型的畫筆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.