WPF中的全局样式

3

我正在学习如何在WPF中使用样式,根据我在网络上找到的信息,如果我按照以下方式定义样式(使用目标类型):

<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>

我希望为我的应用程序中的所有按钮应用这种样式。但是似乎我的按钮仍然保持原样。 在主窗口中,我将资源字典添加到资源集合中,并插入了几个按钮,但我的按钮始终看起来一样。以下是主窗口的代码:

<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>

为什么按钮样式没有应用?

可能是 https://dev59.com/WkzSa4cB1Zd3GeqPmnGm 的重复问题。 - Dan J
2个回答

6
根据这个问题的答案:使用样式设置工具栏按钮尺寸 ToolBar 应用了自己的样式到按钮上。可以通过资源键 ToolBar.ButtonStyleKey 访问该样式。使用该键设置你的样式,而不仅仅是针对 Button 类型进行定位,你就可以完成设置:
<Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="Button">
    <Setter Property="Width" Value="100" />
</Style>

4

已经有一个涉及全局样式的答案了,如果您想为每个按钮明确定义自己的样式(也许在您项目的未来),您需要给样式命名:

<Style x:Key="buttonStyleOne" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Black"/>
</Style>

然后将其应用于您希望通过按钮使用该样式的位置:

<Button Style="{DynamicResource buttonStyleOne}">Content!</Button>

1
值得注意的是,这也适用于放置在工具栏内的按钮。+1 - Dan J

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接