Image.Height TemplateBinding does not work

2020-04-21 03:30发布

问题:

I have created a CustomControl implemented from Button class in WPF.

public class ImageButton : Button
{
      ...

       public int ImageHeight
       {
           get { return (int)GetValue(ImageHeightProperty); }
           set { SetValue(ImageHeightProperty, value); }
       }
       public static readonly DependencyProperty ImageHeightProperty =
           DependencyProperty.Register("ImageHeight", typeof(int), typeof(ImageButton), new UIPropertyMetadata(32)); 

       ...
}

And I have resource template like this:

<Setter Property="Template">
   <Setter.Value>
     <ControlTemplate TargetType="{x:Type custom:ImageButton}">
       <Border>
         <StackPanel>
          <Image Name="image" Height="{TemplateBinding ImageHeight}"/>
          <TextBlock Text="{TemplateBinding Text}" />
         </StackPanel>
       </Border>
     <ControlTemplate.Triggers>
   </ControlTemplate>
 </Setter.Value>

ImageHeight dependecy property doesn't binding. When I write like as below it works successful.

Height="32"

What is wrong with this?

回答1:

Did you try using {Binding RelativeSource={RelativeSource TemplatedParent}, Path=Progress} instead ?

See these answers for more details...

WPF TemplateBinding vs RelativeSource TemplatedParent

Binding custom dependency property to custom WPF style

hope this helps