我有一系列应用了样式的 ToggleButtons。我希望能够在选中按钮时更改背景颜色。每个 ToggleButton 都分配给具有以下代码的相同 Checked 事件。
Private Sub togAnswer_Checked(ByVal sender as Object, ByVal e as System.Windows.RoutedEventArgs)
'togAnswer was clicked....
Dim togC as ToggleButton
Dim togS as String = TryCast(sender, ToggleButton).Name.ToString()
'Cycle through all answers and set style
Dim bc = New BrushConverter()
For x = 1 to 3
togC = DirectCast(FindName("togAnswer" & x), ToggleButton)
If togS = "togAnswer" & x.ToString Then
'Set ToggleButton to selected colour
togC.Background = DirectCast(bc.ConvertFrom("#AAFF8020"), Brush)
Else
'Set other ToggleButtons to unselected colour
togC.Background = DirectCast(bc.ConvertFrom("#AA000000"), Brush)
End If
Next
End Sub
该代码正确识别源 ToggleButton 但不更改颜色。
分配给 ToggleButtons 的样式是:
<Style x:Key="GlassToggleButton" TargetType="{x:Type ToggleButton}">
<Setter Property="FontSize" Value="24" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border x:Name="ToggleBorder"
CornerRadius="0 15 0 15"
Background="#AA000000"
BorderBrush="#99FFFFFF"
RenderTransformOrigin="0.5,0.5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="1.7*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" CornerRadius="0,14,0,0">
<Border.Background>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#02FFFFFF" Offset="0"/>
<GradientStop Color="#55FFFFFF" Offset="0.5"/>
<GradientStop Color="#11FFFFFF" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
</Border>
<ContentPresenter x:Name="ToggleContentPresenter"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Grid.RowSpan="2" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="RenderTransform" TargetName="ToggleBorder">
<Setter.Value>
<TransformGroup>
<ScaleTransform ScaleX="0.95" ScaleY="0.95"/>
</TransformGroup>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="#AAFF8020" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="#AAFF8020" />
</Trigger>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Background" Value="#AA000000" />
</Trigger>
<Trigger Property="IsChecked" Value="{x:Null}">
<Setter Property="Background" Value="#AA000000" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>