Search code examples
wpfbindingtemplatebindingthickness

How to TemplateBind to BorderThickness.Top (or Bottom or Left or Right)?


I wonder if it is possible to bind a structure element like BorderThickness.Top to TemplatedParent's corresponding property. I have tried

<Border Margin="0" Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}">
    <Border.BorderThickness>
        <Thickness Left="0" Right="0" Top="{TemplateBinding BorderThickness.Top}" Bottom="{TemplateBinding BorderThickness.Bottom}"/>
    </Border.BorderThickness>
</Border>

The reason i want to do this is i want Left and Right to be 0 and only Top and Bottom be bound.

Thanks in advance.


Solution

  • This is not possible because Thickness is a value-type - you can only create bindings on dependency properties of dependency objects.

    What you could do is binding BorderThickness as normal:

    <Border Margin="0" 
            Padding="{TemplateBinding Padding}" 
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness, Converter={StaticResource ThicknessConverter}}" />
    

    then use a converter to return an appropriately modified Thickness:

    object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
        var thickness = (Thickness) value;
        return new Thickness( 0.0, thickness.Top, 0.0, thickness.Bottom );
    }
    

    You could even use ConverterParameter to specify which parts of the Thickness to clear.