zoukankan      html  css  js  c++  java
  • WPF中自定义路由事件

    public class MyButtonSimple: Button
    {
        // Create a custom routed event by first registering a RoutedEventID
        // This event uses the bubbling routing strategy
        public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
            "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButtonSimple));
    
        // Provide CLR accessors for the event
        public event RoutedEventHandler Tap
        {
                add { AddHandler(TapEvent, value); } 
                remove { RemoveHandler(TapEvent, value); }
        }
    
        // This method raises the Tap event
        void RaiseTapEvent()
        {
                RoutedEventArgs newEventArgs = new RoutedEventArgs(MyButtonSimple.TapEvent);
                RaiseEvent(newEventArgs);
        }
        // For demonstration purposes we raise the event when the MyButtonSimple is clicked
        protected override void OnClick()
        {
            RaiseTapEvent();
        }
    
    }
    <Window  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:custom="clr-namespace:SDKSample;assembly=SDKSampleLibrary"
        x:Class="SDKSample.RoutedEventCustomApp"
    
        >
        <Window.Resources>
          <Style TargetType="{x:Type custom:MyButtonSimple}">
            <Setter Property="Height" Value="20"/>
            <Setter Property="Width" Value="250"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="Background" Value="#808080"/>
          </Style>
        </Window.Resources>
        <StackPanel Background="LightGray">
            <custom:MyButtonSimple Name="mybtnsimple" Tap="TapHandler">Click to see Tap custom event work</custom:MyButtonSimple>
        </StackPanel>
    </Window>

    备注:在MVVM模式中,不能直接绑定控件的路由事件到ViewModel,可以将事件绑定后台.cs中的方法,然后再调用ViewModel中的方法。

    .cs文件:

    private void TapHandler(object sender, RoutedEventArgs e)
    {
        ViewModel vm = this.DataContext;
        vm.method;
    }
  • 相关阅读:
    CSS居中布局
    Dubbo源码学习(二)
    golang实现chunk方式的查询
    吴裕雄--天生自然 PHP开发学习:MySQL 插入数据
    吴裕雄--天生自然 PHP开发学习:连接 MySQL、创建表
    吴裕雄--天生自然 JAVA开发学习:基础语法
    吴裕雄--天生自然 PHP开发学习:高级
    吴裕雄--天生自然 PHP开发学习:多维数组
    吴裕雄--天生自然 PHP开发学习:表单
    吴裕雄--天生自然 PHP开发学习:表单
  • 原文地址:https://www.cnblogs.com/bincoding/p/8665489.html
Copyright © 2011-2022 走看看