简体   繁体   English

如何覆盖用户控件中的onTouchUp,它不仅可以用于触发此用户控件上的事件,还可以用于整个应用程序

[英]How to override the onTouchUp in the user control which can be used to fire the event not only on this user control, but whole application

I am a new to the C# and WPF. 我是C#和WPF的新手。 Right now, I want to override onTouchUp event in my user control. 现在,我想在我的用户控件中覆盖onTouchUp事件。 Then I can add user control in the references for reuse. 然后我可以在引用中添加用户控件以供重用。 The problem is each time I want to test this event on the application, the event only fires at area of user control, not whole screen. 问题是每次我想在应用程序上测试此事件时,事件仅在用户控件区域触发,而不是整个屏幕。 Does anyone have a solution for this? 有人有解决方案吗?

Basically, you need to attach to PreviewTouchUp event on a element, that covers the interactive area. 基本上,您需要在元素上附加到PreviewTouchUp事件,该元素覆盖交互区域。 It may be application wndows as well. 它也可能是应用程序窗口。 Handling mouse or touch events outside window is not recommended. 不建议在窗口外处理鼠标或触摸事件。

Here's an example, how can you attach any behaviour to any element directly in xaml: 这是一个示例,如何将任何行为直接附加到xaml中的任何元素:

  <Window  my:MyBehaviour.DoSomethingWhenTouched="true" x:Class="MyProject.MainWindow">



public static class MyBehaviour
{
    public static readonly DependencyProperty  DoSomethingWhenTouchedProperty = DependencyProperty.RegisterAttached("DoSomethingWhenTouched", typeof(bool), typeof(MyBehaviour), 
        new FrameworkPropertyMetadata( DoSomethingWhenTouched_PropertyChanged));

    private static void  DoSomethingWhenTouched_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uiElement = (UIElement)d;

        //unsibscribe firt to avoid multiple subscription
        uiElement.PreviewTouchUp -=uiElement_PreviewTouchUp;

        if ((bool)e.NewValue){
            uiElement.PreviewTouchUp +=uiElement_PreviewTouchUp;
        }
    }

    static void uiElement_PreviewTouchUp(object sender, System.Windows.Input.TouchEventArgs e)
    {
        //you logic goes here
    }

    //methods required by wpf conventions
    public static bool GetDoSomethingWhenTouched(UIElement obj)
    {
        return (bool)obj.GetValue(DoSomethingWhenTouchedProperty);
    }

    public static void SetDoSomethingWhenTouched(UIElement obj, bool value)
    {
        obj.SetValue(DoSomethingWhenTouchedProperty, value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM