首页 > 解决方案 > 绑定到 xaml 中另一个控件样式定义的默认属性值

问题描述

我有一个CustomControl并且想要拥有TextBox默认样式定义的默认值。我不知道这是否可能。

这是我迄今为止尝试过的,但没有成功。但在这里你可以看到我的想法。

我的默认实现来更改默认样式TextBox(例如在 app.xaml 中将其应用于全局)

<Style TargetType="TextBox">
    <Setter Property="BorderThickness" Value="2"/>
</Style>

在这里我想得到'2'的值。

<Style TargetType="controls:CustomControl">
    <Setter Property="BorderThickness" Value="{Binding Source={x:Static TextBox.BorderThicknessProperty}}"/>
</Style>

标签: wpfxaml

解决方案


BorderThicknessa 的属性的默认值在运行时最终应用于 a 的实例的TextBox默认样式中定义。TextBoxTextBox

所以你不能做这样的事情:

<Style TargetType="controls:CustomControl">
    <Setter Property="BorderThickness" Value="{Binding Source={x:Static TextBox.BorderThicknessProperty}}"/>
</Style>

TextBox...除非您绑定到使用默认样式的实际实例。

您可以查看默认模板TextBox并简单地复制其默认BorderThickness属性值1

<Style TargetType="controls:CustomControl">
    <Setter Property="BorderThickness" Value="1"/>
</Style>

显然,您还可以从多个 绑定到一个类的属性Style,例如:

<Style TargetType="controls:CustomControl">
    <Setter Property="BorderThickness" Value="{Binding Thickness, Source={StaticResource settings}}"/>
</Style>

推荐阅读