首页 > 解决方案 > WPF C# 使用资源以获得一致的外观

问题描述

我正在开发一个 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,我无法使其正常工作,并且我必须在每个 groupbox 内重复提供画笔、角落等的所有格式。

问题可能是什么?任何建议将不胜感激。

此致。

标签: c#wpfxaml

解决方案


样式定位边框不能应用于不同类型的元素,例如 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,但应用了其他属性


推荐阅读