如何在WPF中触发选中或取消选中事件后启用/禁用复选框
本文关键字:启用 事件 复选框 WPF 取消 | 更新日期: 2023-09-27 18:23:46
我为复选框控件编写了一个自定义模板,它显示绿色表示选中,显示红色表示未选中。我想让复选框控件在触发check/uuncheck事件后禁用3秒钟,然后恢复其启用状态。如何将函数集成到我的自定义模板?
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<Grid x:Name="LayoutRoot">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CheckStates">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="grid1">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid x:Name="grid">
<Rectangle HorizontalAlignment="Left" Height="22" Stroke="White" VerticalAlignment="Top" Width="22">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,0" StartPoint="0.5,1">
<GradientStop Color="#FF86CC6E" Offset="0.022"/>
<GradientStop Color="#FF47E211" Offset="0.81"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" FontFamily="Arial Black" FontSize="10.667" Text="{TemplateBinding Content}" />
</Grid>
<ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content=""/>
<Grid x:Name="grid1">
<Rectangle HorizontalAlignment="Left" Height="22" Stroke="White" VerticalAlignment="Top" Width="22">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,0" StartPoint="0.5,1">
<GradientStop Color="#FFDE6666" Offset="0.022"/>
<GradientStop Color="#FFFB2611" Offset="0.81"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" FontFamily="Arial Black" FontSize="10.667" Text="{TemplateBinding Content}" />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
至少有一种方法可以像这样使用Trigger
:
<ControlTemplate TargetType="{x:Type CheckBox}">
<ControlTemplate.Resources>
<Storyboard x:Key="ffIsEnabled" Storyboard.TargetProperty="IsEnabled">
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsEnabled">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
<DiscreteBooleanKeyFrame KeyTime="0:0:3" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource ffIsEnabled}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource ffIsEnabled}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
<!-- ... -->
</ControlTemplate>