gpt4 book ai didi

wpf - 如何设置覆盖 WPF 中全局样式的特定控件元素设置?

转载 作者:行者123 更新时间:2023-12-05 05:12:30 25 4
gpt4 key购买 nike

我已经通过应用程序范围的资源字典为我的应用程序中的按钮定义了一个全局样式。样式如下所示(来自另一个 SO 示例):

<Style TargetType="Button">
<Setter Property="Foreground" Value="White"/>
<Setter Property="Background" Value="{DynamicResource BaseButtonBG}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<!-- Triggers here -->>
</Style.Triggers>

它有效。但是我需要直接为我的一些按钮分配特定的值,比如边距和填充以对齐它们。我还希望能够覆盖单个按钮样式中的颜色属性。

似乎我直接在特定按钮上设置的任何属性都被完全忽略,只使用全局样式的属性。我该如何克服这个问题?

更新:阐明我想要什么: 在 HTML/CSS 世界(比污垢更古老)中,您可以将样式类添加到元素,但您也可以将属性直接分配给覆盖类值的元素。这就是我想在 WPF 中完成的。

更新 2人们可能认为这个问题很愚蠢,因为解决方案应该是显而易见的。然而,根据我的个人测试,似乎存在一个错误,即 Padding 根本不会改变,除非你专门将它绑定(bind)到一个控件模板中。这种行为似乎随着属性的不同而改变。由于我最初尝试覆盖某个属性的尝试特别涉及 Padding,但它没有奏效,所以我不得不构建此解决方法。

最佳答案

好的,设计中的表单:

enter image description here

表单的 XAML 代码:

<Window.Resources>

<Style TargetType="Button">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>


<Grid>
<Button Content="Button" x:Name="btnNo1" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" x:Name="btnNo2" HorizontalAlignment="Left" Margin="135,10,0,0" VerticalAlignment="Top" Width="120"/>

</Grid>

在 RunTime 中,我们将通过在 CS 文件中使用以下代码来更改 Margin:

public MainWindow()
{
InitializeComponent();

btnNo2.Margin = new Thickness(100, 100, 100, 100);
}

结果将是:

enter image description here



您能否为需要自定义边距/填充的按钮创建和使用新样式?

<Style x:Key="SpecialButtonType1" BasedOn="{StaticResource ResourceKey=CommonButtonStyle}">
...
</Style>

和改变

<Style TargetType="Button">

<Style TargetType="Button" x:Key="CommonButtonStyle">

关于wpf - 如何设置覆盖 WPF 中全局样式的特定控件元素设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54495383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com