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

时间:2014-10-16 06:53:23

标签: c# wpf itemscontrol eventtrigger

我正在尝试使用Interactivity.EventTrigger以下面显示的方式捕获我的自定义事件(TextUpdateEvent)。但是这段代码引发了System.ArgumentException,并在类型“工具: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.
}

1 个答案:

答案 0 :(得分:1)

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

public event MyTextBoxUpdateHandler TextUpdateEvent;

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

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

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