2016-08-16 150 views
0

我有一個RadioButton是作爲ItemsControl DataTemplate的一部分動態設置的。根據屬性更改RadioButton的樣式

<RadioButton GroupName="Ratings"> 
    <RadioButton.Content> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="{Binding Score}" /> 
     <TextBlock Text=" - " /> 
     <TextBlock Text="{Binding Description}" /> 
    </StackPanel> 
    </RadioButton.Content> 
</RadioButton> 

我有兩個預定義的樣式(MyCheckedStyle1MyUncheckedStyle2),它做工精細單獨當我設置單選按鈕的Style=財產,但我還沒有找到一種方法基於它的財產器isChecked改變風格。

大多數方法我試圖嘗試給我

所以僞

if IsChecked = true then 
    style = MyCheckedStyle1 
else if IsChecked = false then 
    style = MyUncheckedStyle1 

異常有關Style object is not allowed to affect the Style property of the object to which it applies.(如的ContentTemplate觸發),我可以用代碼隱藏做到這一點,但我想,如果要避免這種情況可能並將邏輯放在XAML中。

+1

將樣式應用於無線電的「Parent」,然後用觸發器通過IsChecked屬性更改無線電的樣式。另一種方式將樣式應用於無線電本身 然後用觸發器通過IsChecked屬性更改ControlTemplate。 – codeDom

+0

樣式不是由我定義的,我無法更改它們。你的第一個選擇聽起來像是可行的,你能提供一個答案,進一步解釋你的意思嗎? –

+0

難道你不能只改變Checked/Unchecked事件背後的代碼樣式嗎? –

回答

3

將樣式應用於無線電父母,然後使用觸發器通過IsChecked屬性更改無線電的樣式。

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="101" Width="264"> 
    <Window.Resources> 

     <Style x:Key="MyCheckedStyle1" TargetType="RadioButton"> 
      <Setter Property="Background" Value="Red"/> 
     </Style> 
     <Style x:Key="MyCheckedStyle2" TargetType="RadioButton"> 
      <Setter Property="Background" Value="Blue"/> 
     </Style> 

     <Style x:Key="ParentStyle" TargetType="ContentControl"> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate> 
         <RadioButton Name="RadioButton1" GroupName="Ratings" > 
          <RadioButton.Content> 
           <StackPanel Orientation="Horizontal"> 
            <TextBlock Text="{Binding Score}" /> 
            <TextBlock Text=" - " /> 
            <TextBlock Text="{Binding Description}" /> 
           </StackPanel> 
          </RadioButton.Content> 
         </RadioButton> 
         <ControlTemplate.Triggers> 
          <Trigger SourceName="RadioButton1" Property="IsChecked" Value="True"> 
           <Setter TargetName="RadioButton1" Property="Style" 
             Value="{StaticResource MyCheckedStyle1}"/> 
          </Trigger> 
          <Trigger SourceName="RadioButton1" Property="IsChecked" Value="False"> 
           <Setter TargetName="RadioButton1" Property="Style" 
             Value="{StaticResource MyCheckedStyle2}"/> 
          </Trigger> 
         </ControlTemplate.Triggers> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Window.Resources> 
    <Grid> 
     <ListBox> 
      <ContentControl Style="{StaticResource ParentStyle}"/> 
      <ContentControl Style="{StaticResource ParentStyle}"/> 
     </ListBox> 
    </Grid> 
</Window>