[英]WPF button style and template
所以我有按鈕及其樣式:
<Style TargetType="Button" x:Key="BaseButtonStyle">
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Width" Value="120" />
<Setter Property="Height" Value="30" />
<Setter Property="BorderBrush" Value="#1FA3FF" />
</Style>
<Style TargetType="{x:Type Button}" x:Key="MyButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Background" Value="#1FA3EB" />
<Setter Property="Foreground" Value="#FFFFFF" />
</Style>
<Button Style="{StaticResource MyButtonStyle}" Content="My text" />
它工作正常,我得到以下結果(藍綠色背景不是Button的一部分,它屬於Window):
但是,然后我想替換按鈕的內容並更改我的樣式,因此:
<Style TargetType="{x:Type Button}" x:Key="MyButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Background" Value="#1FA3EB" />
<Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="√" />
<TextBlock Text="{TemplateBinding Button.Content}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
現在我的按鈕變得糟糕了:
如您所見,我的按鈕丟失了邊框和背景,並且當鼠標懸停在其上方時,它的視圖也沒有改變。 我在哪里錯了,我應該怎么做才能防止它?
UPD
當我做這樣的事情:
<Style TargetType="{x:Type Button}" x:Key="MyButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Background" Value="#1FA3EB" />
<Setter Property="Foreground" Value="#FFFFFF" />
<Setter Property="Content" >
<Setter.Value>
<StackPanel Orientation="Horizontal">
<TextBlock Text="√" />
<TextBlock Text="{TemplateBinding Button.Content}" />
</StackPanel>
</Setter.Value>
</Setter>
</Style>
然后我得到這個結果:
如您所見,這類似於第一個結果,其中沒有選中標記
默認的外觀和功能Button
在默認定義ControlTemplate
的Button
(你可以發現,在按鈕樣式和模板頁面上MSDN)。 更改ControlTemplate
,默認外觀和行為現在消失了,並替換為普通的StackPanel
和TextBlock
元素。
為控件提供新的ControlTemplate
,最好從默認的ControlTemplate
開始並進行一些小的更改,直到您具有所需的外觀。 這是對Style
的略微擴展,提供了一些基本的鼠標懸停功能:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="Black" BorderThickness="1" CornerRadius="3">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Setter Property="Background" Value="LightBlue" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightGreen" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel Orientation="Horizontal">
<TextBlock Text="√" />
<TextBlock Text="{TemplateBinding Button.Content}" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
您可以從MSDN上的ControlTemplate
類頁面找到有關ControlTemplate
的更多信息。
如果只需要更改按鈕的內容,則可以通過以下方式進行操作:
<Button Style="{StaticResource BaseButtonStyle}">
<!-- This is the content -->
<StackPanel Orientation="Horizontal">
<TextBlock Text="√" />
<TextBlock Text="{Binding ButtonTextBinding}" />
</StackPanel>
</Button>
這樣,您就不會失去基本樣式。 button content屬性是一個對象,因此它需要任何東西。 更改按鈕的控制模板后,有關背景,邊框,鼠標懸停,按下狀態等的所有信息都會丟失。 重設任何WPF控件樣式的最佳方法是從MSDN中獲取並修改基本模板,而不是從頭開始。 您可以在此處找到按鈕模板:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.