WPF在Thumb上处理双击事件并将其作为另一个控件上的新事件引发

时间:2016-07-11 09:47:13

标签: wpf routedevent

我尝试了没有运气的行为

行为:

    public sealed class BubbleDoubleClickEvent : Behavior<UIElement>
    {
        #region TargetElement
        public UIElement TargetElement
        {
        get { return (UIElement)GetValue( TargetElementProperty ); }
        set { SetValue( TargetElementProperty, value ); }
    }

    // Using a DependencyProperty as the backing store for TargetElement.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TargetElementProperty =
        DependencyProperty.Register( "TargetElement", typeof( UIElement ), typeof( BubbleDoubleClickEvent ) );
    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.PreviewMouseDown += AssociatedObject_PreviewMouseDown;
    }

    private void AssociatedObject_PreviewMouseDown( object sender, MouseButtonEventArgs e )
    {
        if( e.ClickCount == 2 )
        {
            e.Handled = true;
            var e2 = new MouseButtonEventArgs( e.MouseDevice, e.Timestamp, e.ChangedButton );
            e2.RoutedEvent = Control.PreviewMouseDoubleClickEvent;

            var target = TargetElement ?? AssociatedObject;
            target.RaiseEvent( e2 );
        }
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewMouseDown -= AssociatedObject_PreviewMouseDown;
        base.OnDetaching();
    }
}

XAML:

<Grid>
   <ContentPresenter x:Name="contentPresenter" Content="{Binding}"    ContentTemplate="{Binding ..., Path=ItemTemplate }" />

   <Thumb x:Name="moveThumb" >
        <i:Interaction.Behaviors>
            <behaviors:BubbleDoubleClickEvent TargetElement="{Binding   ElementName=contentPresenter}"/>
        </i:Interaction.Behaviors>
   </Thumb>
</Grid>

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

上面的代码效果很好,但目标控件没有收到事件OnPreviewMouseDoubleClick所以我不得不添加一个实例处理程序来管理这样的事件:

 this.AddHandler( Control.PreviewMouseDoubleClickEvent,
     new MouseButtonEventHandler( ( target, args ) =>
     {
       //do stuff
       args.Handled = true;
     } ), false );