c# - 如何在代码隐藏中调用 Prism 事件

标签 c# wpf xaml prism

我是 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/

相关文章:

c# - 当内部调用不是自然异步时,如何创建自然异步方法?

c# - Entity Framework Core - 多个 DbContext 单数据库

c# - 如何在WPF中使用Flyout?

c# - 如何在 WebAPI 中将 null 值传递给可空类型

c# - 为什么使用 Log4Net 而不是只写入我的数据库?

c# - 比较两个以逗号分隔的字符串是否匹配的最短代码是什么?

WPF DataGrid 控件模板

wpf - 在 WPF DataGrid 为空时显示 "No record found"消息

c# - 当 DataTemplate 具有可见性绑定(bind)时,WPF ListBox 自动宽度更改不正确

XAML 按钮导致 Xamarin 应用程序在启动时崩溃