gpt4 book ai didi

c# - 如何在控件模板资源中重用定义的样式

转载 作者:行者123 更新时间:2023-11-30 17:55:36 24 4
gpt4 key购买 nike

我是 WPF 新手。我不知道该怎么做。

我定义了这个样式 -

<Style TargetType="{x:Type Button}" x:Key="StandardButton">

<Setter Property="Background" Value="{StaticResource LightBackground}"/>

<Setter Property="Foreground" Value="{StaticResource Foreground}"/>

</Style>

我有一个控件模板 -

<ControlTemplate x:Key="ExpanderTemplate" TargetType="{x:Type Expander}">

<ControlTemplate.Resources>

<Style TargetType="{x:Type Button}" /* Here I need to put above defined style */></Style>

</ControlTemplate.Resources>

</ControlTemplate>

最佳答案

如果您希望ControlTemplate 中的所有Buttons 都使用Style,只需从中删除x:Key样式并添加到 ControlTemplate.Resources

<ControlTemplate.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="{StaticResource LightBackground}"/>
<Setter Property="Foreground" Value="{StaticResource Foreground}"/>
</Style>
</ControlTemplate.Resources>
具有 x:Key

Styles 必须像 Style="{StaticResource StandardButton}" 一样在控件上声明,才能应用对于 Resources 范围内的所有控件,您只需声明 TargetType

如果您已经在更高级别的 Resources 中定义了一个 Style 并且您想要应用到您的 中的所有 Buttons ControlTemplate 您可以使用 BasedOn 属性。

例子:

<ControlTemplate x:Key="ExpanderTemplate" TargetType="{x:Type Expander}">
<ControlTemplate.Resources>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource StandardButton}" />
</ControlTemplate.Resources>
</ControlTemplate>

这会将 StandardButton Style 应用于定义的 Resources 范围内的所有按钮,在本例中是所有 ExpanderTemplate

中的按钮

关于c# - 如何在控件模板资源中重用定义的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14930835/

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