WPF属性触发器不产生效果
我XAML页面设置这样一个触发器,为什么没有起到效果呢
<Window x:Class="ProDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Name="FrmMain"> <Window.Resources> <Style TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="Black"/> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Content="Button" Height="43" Margin="12,48,356,218" Name="btn" Width="135" Click="btn_Click" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="12,20,0,0" Name="txt" VerticalAlignment="Top" Width="479" /> </Grid></Window>
</StackPanel>
</Border>
</Border>
</Grid>
<!--触发器-->
<ControlTemplate.Triggers>
<!--鼠标移入移出-->
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="6" Duration="0:0:0.2" Storyboard.TargetName="back" Storyboard.TargetProperty="(Border.BitmapEffect).(OuterGlowBitmapEffect.GlowSize)" />
<ColorAnimation To="#AFFF" BeginTime="0:0:0.2" Duration="0:0:0.2" Storyboard.TargetName="fore" Storyboard.TargetProperty="(Border.Background).(LinearGradientBrush.GradientStops)[0].(GradientStop.Color)" />
<ColorAnimation To="#3FFF" BeginTime="0:0:0.2" Duration="0:0:0.2" Storyboard.TargetName="fore" Storyboard.TargetProperty="(Border.Background).(LinearGradientBrush.GradientStops)[1].(GradientStop.Color)" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="back" Storyboard.TargetProperty="(Border.BitmapEffect).(OuterGlowBitmapEffect.GlowSize)" />
<ColorAnimation Duration="0:0:0.2" Storyboard.TargetName="fore" Storyboard.TargetProperty="(Border.Background).(LinearGradientBrush.GradientStops)[0].(GradientStop.Color)" />
<ColorAnimation Duration="0:0:0.2" Storyboard.TargetName="fore" Storyboard.TargetProperty="(Border.Background).(LinearGradientBrush.GradientStops)[1].(GradientStop.Color)" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
[解决办法]
在WPF中,触发器仅有效于样式和模板中,并且需要EventTriggers支持。
如果需要将触发器用于样式和模板外,可以将触发器套在一下代码:
<Control> <Control.Template> <ControlTemplate> <!-- 触发器代码 --> </ControlTemplate> </Control.Template></Control>