BarryLib
BarryLib

Reputation: 299

WPF Trigger not working

I am trying to use triggers to modify the property of my control.I have a RadioButton and a Border, I want to modify the border Background when the RadioButton IsSelected. So here is my code:

<Border BorderBrush="{DynamicResource MaterialDesignDivider}">
     <RadioButton IsChecked="{Binding Erase_IsSelected}" Content="E">
         <RadioButton.Resources>
              <Style TargetType="{x:Type RadioButton}">
                  <Style.Triggers>
                       <Trigger Property="IsChecked" Value="True">
                            <Setter Property="Background" Value="{DynamicResource MaterialDesignSelection}" />
                       </Trigger>
                  </Style.Triggers>
              </Style>
         </RadioButton.Resources>
     </RadioButton>
</Border>

This seems don't work, how should I fix it? Thanks!

Upvotes: 0

Views: 741

Answers (2)

mm8
mm8

Reputation: 169150

Use a Style for the Border that binds to the IsChecked property of the RadioButton:

<Border BorderBrush="{DynamicResource MaterialDesignDivider}">
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=rb}" Value="True">
                    <Setter Property="Background" Value="{DynamicResource MaterialDesignSelection}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <RadioButton x:Name="rb" IsChecked="{Binding Erase_IsSelected}" Content="E" />
</Border>

A RadioButton style cannot change the property of a Border.

Upvotes: 3

Dennis Larisch
Dennis Larisch

Reputation: 573

Add the OnChecked event in your xaml:

<RadioButton Checked="Radiobutton_OnChecked" Content="E">
      <RadioButton.Resources>
          <Style TargetType="{x:Type RadioButton}">
               <Style.Triggers>
                     <Trigger Property="IsChecked" Value="True">
                          <Setter Property="Background" Value="{DynamicResource MaterialDesignSelection}" />
                     </Trigger>
               </Style.Triggers>
          </Style>
      </RadioButton.Resources>
 </RadioButton>

this will create you a function in your .cs like this, where you can change the background:

private void Radiobutton_OnChecked(object sender, RoutedEventArgs e)
{
    RadioButton rdb = (RadioButton) sender;

    rdb.Background = new SolidColorBrush(Colors.Green);
}

Upvotes: -1

Related Questions