【发布时间】:2019-12-25 10:31:59
【问题描述】:
我创建的自定义控件有一个事件如下。
public class Editor : Control
{
...
public event EventHandler<AlarmCollection> AlarmFired = null;
...
}
当触发 TextChanged 事件时,将调用上述事件(如果不为 null)。
private async void TextArea_TextChanged(object sender, TextChangedEventArgs e)
{
...
this.AlarmFired?.Invoke(this, this.alarmList);
...
}
现在我尝试将上述事件绑定到外部的 ViewModel,如下所示。
<DataTemplate DataType="{x:Type documentViewModels:EditorTypeViewModel}">
<editor:Editor FontSize="15" FontFamily="Arial"
KeywordForeground="LightBlue">
<i:Interaction.Triggers>
<i:EventTrigger EventName="AlarmFired">
<mvvm:EventToCommand Command="{Binding AlarmFiredCommand}"
PassEventArgsToCommand="True"
EventArgsConverter="{localConverters:RemoveObjectConverter}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</editor:Editor>
</DataTemplate>
EditorTypeViewModel的定义如下所示。
public class EditorTypeViewModel : DocumentViewModel
{
public event EventHandler<AlarmCollection> AlarmFired = null;
public EditorTypeViewModel(string title) : base(title)
{
}
private RelayCommand<AlarmCollection> alarmFiredCommand = null;
public RelayCommand<AlarmCollection> AlarmFiredCommand
{
get
{
if (this.alarmFiredCommand == null)
this.alarmFiredCommand = new RelayCommand<AlarmCollection>(this.OnAlarmFired);
return this.alarmFiredCommand;
}
}
private void OnAlarmFired(AlarmCollection alarmInfos)
{
this.AlarmFired?.Invoke(this, alarmInfos);
}
}
当我执行上述程序时,没有调用与 RelayCommand 连接的 OnAlarmFired 方法。 我试图找出原因,发现了一个可疑点。
一个可疑点是在调用Editor的TextChanged方法时,Editor的AlarmFired事件的值为null。如下图所示。
我认为 AlarmFired 不为空,因为它会与 Command 连接,但事实并非如此。
我尝试做的是将CustomControl的事件绑定到ViewModel的Command并使用它。
例如,ListView 的 MouseDoubleClick 事件可以绑定到 MouseDoubleClickCommand,如下所示。 当 MouseDoubleClick 事件被触发时,MouseDoubleClickCommand 将获得控制权。
<ListView>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<mvvm:EventToCommand Command="{Binding MouseDoubleClickCommand}"
PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListView>
我想创建一个事件来支持像 ListView 的 MouseDoubleClick 这样的命令转换 (我不想在CustomControl中创建Command,因为事件数量很多)
我应该怎么做才能实现这个目标?
感谢您的阅读。
【问题讨论】:
标签: wpf event-handling command custom-controls