Binding to a DependencyProperty from a ControlTemplate

n0kx 1 Reputation point
2020-03-30T00:52:22+00:00

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 Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,670 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alex Li-MSFT 1,096 Reputation points
    2020-03-30T04:59:16.79+00:00

    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.

    0 comments No comments