【问题标题】:ResourceDictionary Template reference to Self对 Self 的 ResourceDictionary 模板引用
【发布时间】:2024-11-08 13:30:02
【问题描述】:

我有一个自定义按钮(我们称之为 MetroButton),它派生自 Button,并添加了 3 个属性:Size、ImageSource 和 Text。 Size同时描述了控件的Width和Height。

MetroButtons 包含一个模板 - 现在我想将模板分割成一个独立的 ResourceDictionary.xaml - 但是我如何将按钮的宽度和高度引用到自定义属性“大小”?

<ControlTemplate TargetType="Button">
        <Border x:Name="_border"
                Width="{Binding Size,
                                ElementName=_metroButton,
                                UpdateSourceTrigger=PropertyChanged,
                                Mode=TwoWay}"
                Height="{Binding Size,
                                 ElementName=_metroButton,
                                 UpdateSourceTrigger=PropertyChanged,
                                 Mode=TwoWay}"
                Background="{StaticResource DefaultButtonBackgroundColor}"
                BorderBrush="{StaticResource DefaultButtonBorderColor}"
                BorderThickness="{TemplateBinding BorderThickness}">

目前我可以使用 ElementName,因为模板是直接在 MetroButton 类内部定义的 - 如果模板是在类外部定义的,则没有机会引用 ElementName (afaik) - 并使用

RelativeSource={RelativeSource Self}

也不会导致预期的结果 - 那么样式将根本不适用。

有什么解决办法吗?

【问题讨论】:

  • 为什么不将模板放入默认主题xaml?然后控制模板将定位MetroButton 类型,您可以简单地使用TemplateBinding
  • 天啊,你说的太对了——如前所述,我想把模板放到 Default.xaml 中,但我忘记了,我可以直接定位 MetroButton。如果您接受您的评论并将其放入答案中,我将设置为解决方案:)
  • 好吧,不幸的是,这并不容易——我知道为什么乍一看它有效。 MetroButton 被定义为 Button (

标签: c# wpf xaml templates resourcedictionary


【解决方案1】:

RelativeSource={RelativeSource AncestorType={x:Type yourButton}

【讨论】: