question

n0kx avatar image
0 Votes"
n0kx asked AlexLi-MSFT answered

Binding to a DependencyProperty from a ControlTemplate

I have a UserControl with a DependencyProperty called "MyObject." In UserControl.Resources I have a ControlTemplate with a Rectangle and I'm wanting to change the Fill based on a Property in MyObject using DataTriggers.

I'm just not sure how to bind to MyObject from within the ControlTemplate. Any ideas?

Here's some example code. Look for the "Not sure how to bind to the UserControl's DependencyProperty here" comment...

 <UserControl.Resources>
     <ControlTemplate x:Key="SliderThumbVerticalDefault" TargetType="{x:Type Thumb">
         <Rectangle Height="5">
             <Rectangle.Style>
                 <Style TargetType="{x:Type Rectangle}">
                     <Setter Property="Fill" Value"Gray" />
    
                     <Style.Triggers>
                         <DataTrigger Binding="{Binding Path=MyObject.IsOn}" Value="True"> <!-- Not sure how to bind to the UserControl's DependencyProperty here -->
                             <Setter Property="Fill" Value="Red" />
                         </DataTrigger>
                     </Style.Triggers>
                 </Style>
             </Rectangle.Style>
         </Rectangle>
     </ControlTemplate>
 </UserControl.Resources>
windows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AlexLi-MSFT avatar image
0 Votes"
AlexLi-MSFT answered

Hi,

Welcome to our Microsoft Q&A platform!

You can try my code:


    <Style.Triggers>
                                     <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=local:MyUserControl},Path=IsOn}"  Value="True">
                                         <!-- Not sure how to bind to the UserControl's DependencyProperty here -->
                                         <Setter Property="Fill" Value="Red" />
                                     </DataTrigger>
                                 </Style.Triggers>

Thanks.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.