我有一个具有自定义样式的分组框,我正在尝试为其创建可视状态,并在程序上单击按钮时移到这些可视状态。
下面的代码将分组框样式化为并将标题更改为纯蓝色
也要警告仍在学习代码,因此该代码可能混乱或做得不好。
<Style TargetType="GroupBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GroupBox">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="28" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Grid.Row="0"
BorderThickness="1"
BorderBrush="#3c4a55"
Background="#FF0080D4">
<Label Foreground="White">
<ContentPresenter Margin="0"
ContentSource="Header"
RecognizesAccessKey="True" />
</Label>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState Name="Normal"/>
<VisualState x:Name="Orange">
<Storyboard>
<ColorAnimation
Storyboard.TargetName="BackgroundColor"
Storyboard.TargetProperty="Color"
To="{StaticResource CVinYellow}"
/>
</Storyboard>
</VisualState>
<VisualStateGroup.Transitions>
<VisualTransition To="Orange" GeneratedDuration="00:00:01"/>
<VisualTransition To="Normal" GeneratedDuration="00:00:01"/>
</VisualStateGroup.Transitions>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
<Border Grid.Row="1"
BorderThickness="1,1,1,1"
BorderBrush="#25A0DA">
<ContentPresenter Margin="1" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
后面的代码如下:
private void radioButton_Checked(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(testGroupBox, "Orange", true);
}
运行该命令并单击该按钮时,样式完全不会更改,并且不会产生任何错误。
我现在不确定自己在做什么错,您可以用可视状态覆盖自定义控件的颜色吗?
最佳答案
借助thumbmunkeys找出了答案。
VisualStateManager必须是顶部元素。必须将其移动到网格下方。
<Style TargetType="GroupBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GroupBox">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState Name="Normal"/>
<VisualState x:Name="Orange">
<Storyboard>
<ColorAnimation
Storyboard.TargetName="BorderColors"
Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)"
To="{StaticResource CVinYellow}"
/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.RowDefinitions>
<RowDefinition Height="28" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border x:Name="BorderColors"
Grid.Row="0"
BorderThickness="1"
BorderBrush="#3c4a55"
Background="#FF0080D4">
<Label Foreground="White">
<ContentPresenter Margin="0"
ContentSource="Header"
RecognizesAccessKey="True" />
</Label>
</Border>
<Border Grid.Row="1"
BorderThickness="1,1,1,1"
BorderBrush="#25A0DA">
<ContentPresenter Margin="1" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
关于c# - 使用可视状态时,GroupBox header 背景未更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27431692/