WPF C#使用资源实现一致的外观

时间:2018-06-18 12:17:25

标签: c# wpf xaml

我正在开发一个WPF应用程序,我试图定义在整个应用程序中使用的不同常用样式。我在这方面很陌生,所以我不知道是否有一些我误解的东西。无论如何,这里是:

作为一个例子,我创建了一个具有不同通用格式的资源字典。其中之一是边框的格式。定义如下:

<Style x:Key="MainBorderStyle" TargetType="{x:Type Border}">
    <Setter Property="IsEnabled"
            Value="True" />
    <Setter Property="Background"
            Value="Transparent" />
    <Setter Property="BorderBrush"
            Value="Gold" />
    <Setter Property="CornerRadius"
            Value="6" />
    <Setter Property="BorderThickness"
            Value="2" />
    <Setter Property="Padding"
            Value="2" />
</Style>

现在,我想通过不同的元素在整个应用程序中使用这种格式 - 按钮,矩形,组合框等。

目前我无法将边框格式应用于GroupBox控件。我也有GroupBox控件的预定义格式。

在XAML代码的几个地方,我很幸运通过使用代码片段来应用上面的Border设置的引用

<Border Style="{StaticResource MainBorderStyle}" x:Key="SomeKeyID" />

但是,对于GroupBoxes,我无法使其工作,我必须在每个组框内重复提供画笔,角落等的所有格式。

问题是什么?任何建议都将受到高度赞赏。

最好的问候。

1 个答案:

答案 0 :(得分:2)

样式定位边框无法应用于其他类型的元素,例如GroupBox。

您可以创建一个新的MainGroupBoxStyle,从MainBorderStyle复制setter并将其应用于GroupBoxes:

<Style x:Key="MainGroupBoxStyle" TargetType="{x:Type GroupBox}">
    <Setter Property="IsEnabled"
            Value="True" />
    <Setter Property="Background"
            Value="Transparent" />
    <Setter Property="BorderBrush"
            Value="Gold" />
    <Setter Property="BorderThickness"
            Value="2" />
    <Setter Property="Padding"
            Value="2" />
</Style>

或使用没有TargetType的样式:

<Window.Resources>
    <Style x:Key="MainBorderStyle">
        <Setter Property="UIElement.IsEnabled"
                Value="True" />
        <Setter Property="Panel.Background"
                Value="Transparent" />
        <Setter Property="Border.BorderBrush"
                Value="Gold" />
        <Setter Property="Border.CornerRadius"
                Value="16" />
        <Setter Property="Border.BorderThickness"
                Value="2" />
        <Setter Property="Border.Padding"
                Value="2" />
        <Setter Property="Control.Padding"
                Value="2" />
    </Style>
</Window.Resources>
<StackPanel>
    <Border Style="{StaticResource MainBorderStyle}">
        <TextBlock Text="border"/>
    </Border>

    <GroupBox Style="{StaticResource MainBorderStyle}">
        <TextBlock Text="groupBox"/>
    </GroupBox>
</StackPanel>

GroupBox没有CornerRadius,但是应用了其他属性