Search code examples
wpfxaml

Reference object inside XAML template


I have resource dictionary for my radio button which adds textbox to it. I want to add trigger which adds left margin to this textbox but I don't know how to reference it

I marked place where I want to add reference



<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style BasedOn="{StaticResource {x:Type ToggleButton}}"
           TargetType="{x:Type RadioButton}"
           x:Key="MenuButtonTheme">

        <Style.Setters>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="RadioButton">
                        <Grid VerticalAlignment="Stretch"
                                    HorizontalAlignment="Stretch"
                                    Background="{TemplateBinding Background}">
                            <TextBlock Text="{TemplateBinding Property=Content}"
                                    VerticalAlignment="Center"
                                    Margin="20,0,0,0">

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

            </Setter>

            <Setter Property="Background" Value="Transparent"></Setter>
            <Setter Property="BorderThickness" Value="0"></Setter>
        </Style.Setters>
        <Style.Triggers>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Margin" Value="30,0,0,0"></Setter> <!-- Reference TextBlock here -->
            </Trigger>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#424549"></Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</ResourceDictionary>


Solution

  • You need to set triggers not in Style, but in ControlTemplate. Then you can refer to template elements by name:

        <ControlTemplate TargetType="RadioButton">
            <Grid x:Name="PART_Main" VerticalAlignment="Stretch"
                  HorizontalAlignment="Stretch"
                  Background="{TemplateBinding Background}">
                <TextBlock x:Name="PART_TBlock"
                           Text="{TemplateBinding Property=Content}"
                           VerticalAlignment="Center"
                           Margin="20,0,0,0"/>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter TargetName="PART_TBlock" Property="Margin" Value="30,0,0,0"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="PART_Main" Property="Background" Value="#424549"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>