Search code examples
wpfxamlwindows-phone-8

How to Use Trigger to Change RadioButton's StackPanel Background When the RadioButton is Checked


I have multiple RadioButton where a single one is composition of an Image and a TextBlock wrapped with StackPanel

<RadioButton
    Tag="0"
    Grid.Column="0"
    Grid.Row="0"
    Name="rdbOutlook">
    <StackPanel>
        <Image Source="Resources/outlook.png"
            Stretch="Fill"
            Width="50"/>
        <TextBlock Text="Outlook/Hotmail" />
    </StackPanel>
</RadioButton>

I want to set the StackPanel background to such a color when the RadioButton is checked.

How could do that by using Window.Resources to avoid code duplication and ease the modification?


Solution

  • You can use the following code for all RadioButtons containing a StackPanel:

    <Window.Resources>
        <Style TargetType="StackPanel">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type RadioButton}}, Path=IsChecked}" 
                             Value="True">
                    <Setter Property="Background" Value="Thistle" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>