我制作了一个自定义按钮来将命令绑定到(自定义,路由)IsPressedChanged
事件,以便在按下按钮和释放按钮时执行该命令:
<local:CustomButton xmlns:i="http://schemas.microsoft.com/xaml/behaviors" x:Name="MyButton">
<i:Interaction.Triggers>
<i:EventTrigger EventName="CustomIsPressedChanged">
<i:InvokeCommandAction Command="{Binding Path=SomeCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</local:CustomButton>
使用自定义按钮实现:
public partial class CustomButton : Button
{
/* Register a custom routed event using the bubble routing strategy. */
public static readonly RoutedEvent CustomIsPressedChangedEvent = EventManager.RegisterRoutedEvent(
name: "CustomIsPressedChanged",
routingStrategy: RoutingStrategy.Bubble,
handlerType: typeof(RoutedEventHandler),
ownerType: typeof(CustomButton));
/* Provide CLR accessors for assigning an event handler. */
public event RoutedEventHandler CustomIsPressedChanged
{
add { AddHandler(CustomIsPressedChangedEvent, value); }
remove { RemoveHandler(CustomIsPressedChangedEvent, value); }
}
public CustomButton() { InitializeComponent(); }
/* Custom Event handling of the IsPressedChanged event */
protected override void OnIsPressedChanged(System.Windows.DependencyPropertyChangedEventArgs e)
{
/* Call the base class OnIsPressedChanged() method so IsPressedChanged event subscribers are notified. */
base.OnIsPressedChanged(e);
/* Raise custom event */
RaiseEvent(new RoutedEventArgs(routedEvent: CustomIsPressedChangedEvent));
}
}
这完全符合预期。
现在问题来了:
当我尝试传播的价值IsPressed
命令的属性如下所示:
<i:InvokeCommandAction Command="{Binding Path=SomeCommand}"
CommandParameter="{Binding ElementName=MyButton, Path=IsPressed}"/>
传播的值(看起来)总是旧值IsPressed
。当我按下按钮时,调用的命令参数为 false,当我释放按钮时参数为 true。But当我检查的值IsPressed
在事件处理程序内部CustomButton.OnIsPressedChanged()
,它代表了预期的新值。
我的问题是:我该如何传播价值IsPressed
得到正确的值?是否保证命令将始终使用旧值调用?在这种情况下,我可以简单地反转该值,但这对我来说似乎有点阴暗,我真的不想这样做,除非我知道它总是会产生正确的结果。