Themelis
Themelis

Reputation: 4255

How to bind to an element inside a ControlTemplate?

I've created two custom controls in wpf, Control_A and Control_B. Both of them define a ColorProperty. Control_A's ControlTemplate consists of a Control_B instance,

<ControlTemplate 
   TargetType="{x:Type Control_A}">
   <Border 
      Background="{TemplateBinding Background}"
      BorderBrush="{TemplateBinding BorderBrush}"
      BorderThickness="{TemplateBinding BorderThickness}">

      <Control_B />

   </Border>
</ControlTemplate>

What I want is to bind A.Color (target) to B.Color (source). How can this be achieved in XAML?

Upvotes: 2

Views: 61

Answers (2)

Themelis
Themelis

Reputation: 4255

It can be done with a TwoWay binding. This way has it's dissadvantages but it works,

<ControlTemplate 
   TargetType="{x:Type Control_A}">
   <Border 
      Background="{TemplateBinding Background}"
      BorderBrush="{TemplateBinding BorderBrush}"
      BorderThickness="{TemplateBinding BorderThickness}">

      <Control_B 
        Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Color, 
                Mode=TwoWay}"/>

   </Border>
</ControlTemplate>

Upvotes: 2

Klamsi
Klamsi

Reputation: 906

I would try to give Control_B a Name and bind to its color.

Color="{Binding ElementName=Foo, Path=Color}"

Upvotes: 0

Related Questions