如何使用Interactivity.EventTrigger捕获自定义事件

本文关键字:自定义 事件 EventTrigger 何使用 Interactivity | 更新日期: 2023-09-27 18:26:46

我正试图用Interactivey.EventTrigger捕获我的自定义事件(TextUpdateEvent),如下所示。但这段代码引发了System.ArgumentException,并显示消息"在类型"tool:MyTextBox.TextUpdateEvent"中找不到事件"MyTextBox"。"你能告诉我这是怎么回事吗?

<UserControl x:Class="mynamespace.MyControl"
xmlns:local="clr-namespace:mynamespace"
xmlns:info="clr-namespace:mynamespace.info"
xmlns:tool="clr-namespace:mynamespace.tool"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
<Grid>
    <Border>
        <ItemsControl ItemsSource="{Binding MyItems}" Name="itemsControl">
            <ItemsControl.ItemTemplate>                         
                <DataTemplate DataType="info:MyInfo">                             
                    <StackPanel Orientation="Horizontal">                                  
                        <TextBlock Text="{Binding MyComment}"/>
                        <tool:MyTextBox Text="{Binding MyName}" x:Name="myTextBox">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="tool:MyTextBox.TextUpdateEvent"
                                                SourceObject="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type tool:MyTextBox}}}"
                                                SourceName="myTextBox">                         
                                    <ei:CallMethodAction MethodName="UpdateMyInfo" TargetObject="{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Mode=TwoWay}"/>
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </tool:MyTextBox>
                    </StackPanel>                              
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Border>     
</Grid>

namespace mynamespace.tool
{
    //used to judge whether or not the update suceeded
    public delegate bool MyTextBoxUpdateHandler(object sender);
    public partial class MyTextBox : TextBox
    {
        public MyTextBoxUpdateHandler TextUpdateEvent { get; set; }
    }
}

或者,我需要创建一个自定义触发器来捕获我的自定义事件吗?

public class TextUpdateEventTrigger : EventTriggerBase<MyTextBox>
{
    // I don't know what I should do here,
    // since the event I'd like to catch is not a RoutedEvent.
}

如何使用Interactivity.EventTrigger捕获自定义事件

您应该将TextUpdateEvent更改为事件而不是属性。

public event MyTextBoxUpdateHandler TextUpdateEvent;

由于您在代码后面调用方法,因此也不需要附加Interaction触发器:

<tool:MyTextBox 
    x:Name="myTextBox" 
    Text="{Binding MyName}" 
    TextUpdateEvent="UpdateMyInfo" />

DataContext属性不需要绑定到UserControl本身,因为它已经是UserControl的一个分部类,您也可以删除它。