Change the image of the radio button after checked

2019-09-10 07:08发布

问题:

<StackPanel Name="StpAddDel" Orientation="Horizontal" HorizontalAlignment="Right" Margin="5">
   <RadioButton Name="rdbactive" GroupName="actinact" VerticalAlignment="Center" Margin="5,0" Width="50" Height="15" Foreground="Blue">
      <RadioButton.Style>
         <Style TargetType="{x:Type RadioButton}">
            <Setter Property="Template">
               <Setter.Value>
                  <ControlTemplate TargetType="{x:Type RadioButton}">
                     <Grid>
                        <Image Source="c:\image.png" Width="32" Height="32"/>
                        <ContentPresenter/>
                     </Grid>
                  </ControlTemplate>
               </Setter.Value>
            </Setter>
         </Style>
      </RadioButton.Style>
   </RadioButton>
   <RadioButton Name="rdbinactive" GroupName="actinact" VerticalAlignment="Center" Margin="5,0" Width="60" Height="15" Foreground="Blue">
      <RadioButton.Style>
         <Style TargetType="{x:Type RadioButton}">
            <Setter Property="Template">
               <Setter.Value>
                  <ControlTemplate TargetType="{x:Type RadioButton}">
                     <Grid>
                        <Image Source="c:\image.png" Width="32" Height="32"/>
                        <ContentPresenter/>
                     </Grid>
                  </ControlTemplate>
               </Setter.Value>
            </Setter>
         </Style>
      </RadioButton.Style>
   </RadioButton>
   <Button Name="BtnAdd"  Height="20" Width="20" Margin="5,0" Template="{StaticResource AddImgBtnTemplate}" />
   <Button Name="BtnDel" Height="20" Width="20" Margin="5,0" Template="{StaticResource DelImgBtnTemplate}" />
</StackPanel>

In the above code i have 2 radio button i put images on radio buttons , My requirement is i want to change the image of the radio button after it is checked, Please help me with this......

回答1:

You can use ControlTemplate.Triggers for that

<ControlTemplate TargetType="{x:Type RadioButton}">
   <Grid>
       <Image x:Name="PART_Image" Source="c:\image.png" Width="32" Height="32"/>
       <ContentPresenter/>
   </Grid>
   <ControlTemplate.Triggers>
       <Trigger Property="IsChecked" Value="True">
           <Setter TargetName="PART_Image" Property="Source" Value="new source"/>
       </Trigger>
   </ControlTemplate.Triggers>
</ControlTemplate>

Give Image some name and change Source property of that control when IsChecked is true

EDIT

If you want to also "highlight" when mouse is over then you can add for example DropShadowEffect with another Trigger, this time when IsMouseOver is true

<Trigger Property="IsMouseOver" Value="True">
    <Setter TargetName="PART_Image" Property="Effect">
        <Setter.Value>
            <DropShadowEffect ShadowDepth="0" Color="Yellow" Opacity="0.5"/>
        </Setter.Value>
    </Setter>
</Trigger>


标签: wpf xaml mvvm