【问题标题】:Catch custom event by Interactivity.EventTrigger通过 Interactivity.EventTrigger 捕获自定义事件
【发布时间】:2013-10-14 19:57:31
【问题描述】:

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

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 没有调用命令。

我该如何解决这个问题?

【问题讨论】:

  • 我也有同样的问题。在 UserControl 中声明了一个自定义事件。我试图通过交互将它与我的主视图中的命令绑定,但徒劳无功。使用最简单的控件和代码,例如 TextBlock 和 Grid。而已。你解决了吗?

标签: c# wpf wpf-controls eventtrigger


【解决方案1】:

您的代码一切正常。绑定不起作用。我看这个就知道了。

不要在 InvokeCommandAction 中使用 ElementName,因为 InvokeCommandAction 不是 WPF 中 LogicalTree 的一部分。

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

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多