在之前的一篇文章中,我介绍了普通的自定义事件:
【wpf】自定义事件总结(Action, EventHandler)_code bean的博客-CSDN博客_wpf action可以说通过Action和EventHandle,自定义事件是相当的方便简单了。https://blog.csdn.net/songhuangong123/article/details/126251575?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522167602845516800192279505%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=167602845516800192279505&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-2-126251575-null-null.article_score_rank_blog&utm_term=%E4%BA%8B%E4%BB%B6&spm=1018.2226.3001.4450#:~:text=%E3%80%90wpf%E3%80%91%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6%E6%80%BB%E7%BB%93%EF%BC%88Action%EF%BC%8C%20EventHandler%EF%BC%89但是我发现如果你想将自定义的事件,和命令关联起来,普通事件是不行的。
路由事件映射到Command
通常我映射事件到Command如下:
<i:Interaction.Triggers>
<i:EventTrigger EventName="LeftValueChange">
<prism:InvokeCommandAction Command="{Binding ThresholdLeftCmd}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
LeftValueChange是我自定义的事件,如果是普通的事件,这样的换无法触发命令。
自定义路由事件
我们需要自定义一个路由事件:
//声明和注册路由事件
public static readonly RoutedEvent LeftValueChangeEvent =
EventManager.RegisterRoutedEvent("LeftValueChange",
RoutingStrategy.Bubble,
typeof(EventHandler<RoutedEventArgs>),
typeof(RangeSelectionControl));
//CLR事件包装
public event RoutedEventHandler LeftValueChange
{
add { this.AddHandler(LeftValueChangeEvent, value); }
remove { this.RemoveHandler(LeftValueChangeEvent, value); }
}
路由事件的触发
它的出发也和普通事件不一样:
先构造一个 RoutedEventArgs,第一个参数传入路由事件,第二参数传入事件带的参数,
然后调用RaiseEvent出发改事件:
//事件触发
RoutedEventArgs args = new RoutedEventArgs(LeftValueChangeEvent, LeftValue);
this.RaiseEvent(args);
这样事件就能映射到命令了!:)
命令的定义
注意这里的 泛型的类型为:RoutedEventArgs
以及访问参数的方式:OriginalSource
public DelegateCommand<RoutedEventArgs> ThresholdLeftCmd { get; set; }
//二值化
ThresholdLeftCmd = new DelegateCommand<RoutedEventArgs>((x) => {
thresholdLeft = int.Parse(x.OriginalSource.ToString());
UpdataThreshold();
});