正确使用Event

EventTrigger是WPF触发器的一种类型,它根据事件的引发来启动一组操作。以下结合示例介绍其使用方法。 ### 基本使用示例 当鼠标指针进入`ListBoxItem`时,`MaxHeight`属性在0.2秒时间内以动画方式增大为值90;当鼠标离开该项时,该属性在1秒时间内还原为原始值。代码示例如下: ```xml <ListBox> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Style.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="MaxHeight" To="90" Duration="0:0:0.2"/> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="MouseLeave"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="MaxHeight" Duration="0:0:1"/> </Storyboard> </BeginStoryboard> </EventTrigger> </Style.Triggers> </Style> </ListBox.ItemContainerStyle> <ListBoxItem Content="Item 1"/> <ListBoxItem Content="Item 2"/> </ListBox> ``` 上述代码中,定义了`ListBoxItem`的样式,在样式的触发器中使用`EventTrigger`。当`MouseEnter`事件触发时,启动一个故事板,其中的`DoubleAnimation`将`MaxHeight`属性在0.2秒内动画到90;当`MouseLeave`事件触发时,启动另一个故事板,`DoubleAnimation`将`MaxHeight`属性在1秒内恢复到原始值,由于动画能够跟踪原始值,所以`MouseLeave`动画无需指定`To`值 [^2]。 ### 与命令绑定使用示例 在VM部分代码中定义命令,然后在XAML中使用`EventTrigger`触发命令。 VM部分代码: ```csharp public class StudentViewModel : NotificationObject { public StudentViewModel() { Clicked = new ActionCommand(this.Click); } public ICommand Clicked { get; private set; } public void Click(object arg) { //为了演示需要,在这里用了一个MessageBox //应尽量避免在VM中揉杂UI交互功能 MessageBox.Show((arg as Student).StudentName); } } ``` XAML部分代码(假设已正确绑定`StudentViewModel`): ```xml <Button> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <cmd:EventToCommand Command="{Binding Clicked}" PassEventArgsToCommand="True"/> </i:EventTrigger> </i:Interaction.Triggers> <Button.Content>Click Me</Button.Content> </Button> ``` 上述代码中,在VM里定义了`Clicked`命令,在XAML的按钮上使用`EventTrigger`监听`Click`事件,当按钮被点击时,触发`EventToCommand`将事件传递给`Clicked`命令 [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值