【问题标题】:Global styles in WPFWPF 中的全局样式
【发布时间】:2011-09-16 21:29:04
【问题描述】:

我正在学习如何在 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>

为什么不应用 Button 样式?

【问题讨论】:

标签: c# .net wpf styles


【解决方案1】:

根据这个问题的答案:Setting toolbar button sizes using a Style

工具栏正在将自己的样式应用于按钮。可以通过资源键 ToolBar.ButtonStyleKey 访问此样式。使用该键设置您的样式,而不仅仅是定位 Button 类型,您将被设置:

<Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="Button">
    <Setter Property="Width" Value="100" />
</Style>

【讨论】:

    【解决方案2】:

    已经有一个涉及全局样式的答案,如果您想为每个按钮显式定义您的样式(可能在您的项目的未来),您需要命名样式:

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

    然后将其应用到您要通过以下方式使用样式的按钮:

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

    【讨论】:

    • +1 值得注意的是,这也适用于工具栏内的按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2010-10-28
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多