Search code examples
wpfxamldatatrigger

WPF XAML Custom Control: Click "CheckBox", update inner text


I am making a custom control inheriting from CheckBox. Inside I have a TextBox, and when I click the "CheckBox" I want to change the text of the TextBox to say "true". I've tried using DataTriggers, but nothing seems to work. My current setup is,

<Style TargetType="{x:Type local:MyCheckBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCheckBox}"> 
                <Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" 
                      Width="{TemplateBinding Width}"
                      Height="{TemplateBinding Height}">

                    <Border x:Name="CheckBoxTextContainer" CornerRadius="50" Background="Green"
                            VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
                        <TextBlock x:Name="CheckBoxText" Text="False" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                    </Border>

                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

How and where do I define a trigger such that when I click the "CheckBox", it changes the text of "CheckBoxText"


Solution

  • You could do this with a DataTrigger (you would bind with RelativeSource Self to get to IsChecked), but it's simpler to use a regular Trigger:

    <ControlTemplate.Triggers>
        <Trigger Property="IsChecked" Value="True">
            <Setter TargetName="CheckBoxText" Property="Text" Value="True" />
        </Trigger>
    </ControlTemplate.Triggers>
    

    If you want to begin a storyboard,

    <ControlTemplate.Triggers>
        <Trigger Property="IsChecked" Value="True">
            <Setter TargetName="CheckBoxText" Property="Text" Value="True" />
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard ...stuff... />
                </BeginStoryboard>
            </Trigger.EnterActions>
        </Trigger>
    </ControlTemplate.Triggers>