ResourceDictionary 模板引用自我

ResourceDictionary Template reference to Self

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

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

<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 内部定义的 class - 如果模板是在 class 外部定义的,则没有机会引用 ElementName (afaik) - 并使用

RelativeSource={RelativeSource Self}

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

有什么解决办法吗?

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