Global styles in WPF
I'm learning how to use styles in WPF and according to information I found on the net, if I define style this way (with target type):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Black"/>
</Style>
</ResourceDictionary>
...this style will be applied for all buttons in my application. However it seems that my buttons remain the same. In main window I added resource dictionary to resources collection and I inserted a couple of buttons, however my buttons look the same all the time. Here is the code for main window:
<Window x:Class="MCTSTrainingChapter1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="GridResources.xaml"/>
<ResourceDictionary Source="ButtonResources.xaml"/>
</ResourceDictionary.MergedDictionaries>开发者_运维知识库;
</ResourceDictionary>
</Window.Resources>
<DockPanel >
<ToolBar DockPanel.Dock="Top" Height="26" Name="toolBar1" >
<Button x:Name="btnBold" Click="Button_Click">Bold</Button>
<Button Click="Button_Click_1">Italic</Button>
<Slider Name="slider1" Minimum="2" Maximum="72" Width="100" ValueChanged="slider1_ValueChanged"></Slider>
</ToolBar>
<Grid Name="grid1" Background="{StaticResource GridBackgroundBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" Name="listBox1" SelectionChanged="listBox1_SelectionChanged" />
<GridSplitter Grid.Column="1" Margin="0" Width="5" HorizontalAlignment="Left"/>
<RichTextBox Grid.Column="2" Name="richTextBox1"/>
</Grid>
</DockPanel>
</Window>
Why isn't the Button style applied?
As per the answer to this question: Setting toolbar button sizes using a Style
The ToolBar is applying its own style to the button. This style can be accessed by the resource key ToolBar.ButtonStyleKey
. Set up your Style with that key, rather than just Targeting the Button
type, and you'll be set:
<Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="Button">
<Setter Property="Width" Value="100" />
</Style>
There is already an answer involving a global style, if you want to explicitly define your style for each button (perhaps in the future of your project) you would want to name the style:
<Style x:Key="buttonStyleOne" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Black"/>
</Style>
and then apply it to a button you want to use the style via:
<Button Style="{DynamicResource buttonStyleOne}">Content!</Button>
精彩评论