Dan Dan - 1 month ago 14
C# Question

WPF Button ControlTemplate Height binding returns NaN

I'm trying to dynamically set the corner radius of WPF buttons to half of the buttons' height, such that the ends are rounded entirely.

The entry in the Window resources looks like the following, however the

CornerRadius
binding doesn't bind, and passes
NaN
to the value converter.

I've tried replacing the
Binding
with a
TemplateBinding
to no avail. Snoop shows an error on that
CornerRadius
property, being set as
NaN
. Am I missing something obvious here?

<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="grid">
<Border x:Name="border" BorderBrush="#FFFEFEFF" BorderThickness="2" CornerRadius="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Height,Converter={StaticResource HalfConverter}}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
...

Answer

Instead of binding to the control's Height (which is Double.NaN by default), you should bind to its ActualHeight property:

CornerRadius="{Binding Path=ActualHeight, 
                       RelativeSource={RelativeSource TemplatedParent},
                       Converter={StaticResource HalfConverter}}">