我是 WPF 新手。目前,我想让我的添加按钮通过单击或双击来添加项目。但是,当我尝试双击时,它最终会触发两次单击事件。 XAML 代码如下:
<Button.InputBindings>
<MouseBinding Command="{Binding Path=AddCommand}" CommandParameter="{Binding}" MouseAction="LeftClick" />
<MouseBinding Command="{Binding Path=AddCommand}" CommandParameter="{Binding}" MouseAction="LeftDoubleClick" />
我在网上找到了解决办法,就是使用DispatcherTimer来解决问题。我已经在后面的代码中插入了这些:
private static DispatcherTimer myClickWaitTimer =
new DispatcherTimer(
new TimeSpan(0, 0, 0, 1),
DispatcherPriority.Background,
mouseWaitTimer_Tick,
Dispatcher.CurrentDispatcher);
private void btnAdd_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// Stop the timer from ticking.
myClickWaitTimer.Stop();
// Handle Double Click Actions
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
myClickWaitTimer.Start();
}
private static void mouseWaitTimer_Tick(object sender, EventArgs e)
{
myClickWaitTimer.Stop();
// Handle Single Click Actions
}
所以我的问题来了。我已经删除了 XAML 中的 MouseBinding 并想在代码后面调用 AddCommand,但由于 PrismEventAggregator,我在这样做时遇到了问题。 .cs中的AddCommand如下:
private void AddCommandExecute(Object commandArg)
{
// Broadcast Prism event for adding item
this.PrismEventAggregator.GetEvent<AddItemEvent>().Publish(
new AddItemPayload()
{
BlockType = this.BlockType
}
);
}
因此想知道如何在Code behind中调用AddCommand(.cs中的Prism Event)?
注意:该按钮在资源字典中,因此我无法使用按钮名称来调用命令。
最佳答案
您需要创建一个类来订阅您正在发布的事件,然后执行您想要的逻辑。
例如:
public class AddItemViewModel : INotifyPropertyChanged
{
private IEventAggregator _eventAggregator;
public AddItemViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.GetEvent<AddItemEvent>().Subscribe(AddItem);
}
private void AddItem(AddItemPayload payload)
{
// Your logic here
}
}
然后当您发布事件时它会触发订阅者并执行。
关于c# - 如何在代码隐藏中调用 Prism 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807003/