Search code examples
c#wpfxamltemplatesresourcedictionary

ResourceDictionary Template reference to Self


I've got a CustomButton (let's call it MetroButton) which derives from Button and adds 3 properties: Size, ImageSource and Text. Size describes the Width and Height of the Control at the same time.

MetroButtons consists of a Template - now I want to carve-out the Template into a Stand-Alone ResourceDictionary.xaml - but how could I reference the Width and Height of the Button to the custom property "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}">

At the moment I'm able to use ElementName because the Template is defined directly inside the MetroButton class - if the Template is defined outside the class there is no chance to reference the ElementName (afaik) - and using

RelativeSource={RelativeSource Self}

won't lead to the expected result either - then the Styles won't apply at all.

Any solutions?


Solution

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