通过Interactivity.EventTrigger捕获自定义事件

问题描述 投票:5回答:1

我有一个带有事件的简单用户控件:

using System.Windows;

namespace TriggersTest
{
    public partial class MyControl
    {
        public MyControl()
        {
            InitializeComponent();
        }

        public static readonly RoutedEvent ButtonPressedEvent =
            EventManager.RegisterRoutedEvent("ButtonPressed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyControl));

        public event RoutedEventHandler ButtonPressed
        {
            add { AddHandler(ButtonPressedEvent, value); }
            remove { RemoveHandler(ButtonPressedEvent, value); }
        }

        private void OnButtonClick(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs { RoutedEvent = ButtonPressedEvent });
        }
    }
}

并且我想在另一个视图中捕获此事件:

<Window x:Class="TriggersTest.MainWindow"
        Name="Root"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:local="clr-namespace:TriggersTest"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:MyControl>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="ButtonPressed">
                    <i:InvokeCommandAction Command="{Binding MyCommand, ElementName=Root}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </local:MyControl>
    </Grid>
</Window>

已引发事件,但i:EventTrigger不会调用命令。

我该如何解决?

c# wpf wpf-controls eventtrigger
1个回答
-1
投票

您的代码都很好。绑定无效。我只看一眼就能知道。

请勿在InvokeCommandAction中使用ElementName,因为InvokeCommandAction不属于WPF中LogicalTree的一部分。

只需更改您的Binding或使用x:Reference,一切就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.