wpf自定义控件中使用自定义事件
wpf自定义控件中使用自定义事件
1 创建自定义控件及自定义事件
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |     /// <summary>    /// 演示用的自定义控件    /// </summary>    publicclassExtButton : Button    {        publicExtButton()        {            base.Click += ExtButton_Click;        }        privatevoidExtButton_Click(objectsender, RoutedEventArgs e)        {            //定义传递参数            // RoutedPropertyChangedEventArgs<Object> args = new RoutedPropertyChangedEventArgs<Object>("1", "2", ControlLoadOverEvent);            RoutedEventArgs args2 = newRoutedEventArgs(ControlLoadOverEvent, this);            //引用自定义路由事件            this.RaiseEvent(args2);        }        /// <summary>        /// 声明路由事件        /// 参数:要注册的路由事件名称,路由事件的路由策略,事件处理程序的委托类型(可自定义),路由事件的所有者类类型        /// </summary>        publicstaticreadonlyRoutedEvent ControlLoadOverEvent = EventManager.RegisterRoutedEvent("ControlLoadOverEvent", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventArgs<Object>), typeof(ExtButton));        /// <summary>        /// 处理各种路由事件的方法         /// </summary>        publiceventRoutedEventHandler ControlLoadOver        {            //将路由事件添加路由事件处理程序            add { AddHandler(ControlLoadOverEvent, value); }            //从路由事件处理程序中移除路由事件            remove { RemoveHandler(ControlLoadOverEvent, value); }        }    } | 
2 使用并绑定自定义控件的事件
| 1 2 3 4 5 6 7 8 |             <!--i为System.Windows.Interactivity引用-->            <ext:ExtButton x:Name="extButton"Content="绑定自定义事件"HorizontalAlignment="Left"Margin="123,10,0,0"VerticalAlignment="Top"Width="95">                <i:Interaction.Triggers>                    <i:EventTrigger EventName="ControlLoadOver">                        <i:InvokeCommandAction Command="{Binding ButtonLoadOverCommand}"CommandParameter="{Binding ElementName=extButton}"></i:InvokeCommandAction>                    </i:EventTrigger>                </i:Interaction.Triggers>            </ext:ExtButton> | 
3 触发自定义事件后的操作
方式1
| 1 2 3 4 5 6 7 8 9 10 |         publicDelegateCommand<Object> ButtonLoadOverCommand { get; set; }        publicvoidButtonLoadOver(Object obj)        {            //这里的参数为自定义控件对象            ExtButton btn = obj asExtButton;            if(btn != null)            {                var content = btn.Content;            }        } | 
方式2
| 1 2 3 4 5 6 7 |         this.extButton.ControlLoadOver += ExtButton_ControlLoadOver;        privatevoidExtButton_ControlLoadOver(objectsender, RoutedEventArgs e)        {            var btn = (Button)e.Source;            var str = btn.Content;        }
 | 
本文来自博客园,作者:willamyao,转载请注明原文链接:https://www.cnblogs.com/robertyao/p/7447315.html
代码改变世界 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号