zoukankan      html  css  js  c++  java
  • WPF 创建自定义控件及自定义事件

    1 创建自定义控件及自定义事件

    /// <summary>
    /// 演示用的自定义控件
    /// </summary>
    public class ExtButton : Button
    {
    public ExtButton()
    {
    base.Click += ExtButton_Click;
    }

    private void ExtButton_Click(object sender, RoutedEventArgs e)
    {
    //定义传递参数
    // RoutedPropertyChangedEventArgs<Object> args = new RoutedPropertyChangedEventArgs<Object>("1", "2", ControlLoadOverEvent);
    RoutedEventArgs args2 = new RoutedEventArgs(ControlLoadOverEvent, this);
    //引用自定义路由事件
    this.RaiseEvent(args2);

    }
    /// <summary>
    /// 声明路由事件
    /// 参数:要注册的路由事件名称,路由事件的路由策略,事件处理程序的委托类型(可自定义),路由事件的所有者类类型
    /// </summary>
    public static readonly RoutedEvent ControlLoadOverEvent = EventManager.RegisterRoutedEvent("ControlLoadOverEvent", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventArgs<Object>), typeof(ExtButton));
    /// <summary>
    /// 处理各种路由事件的方法
    /// </summary>
    public event RoutedEventHandler ControlLoadOver
    {
    //将路由事件添加路由事件处理程序
    add { AddHandler(ControlLoadOverEvent, value); }
    //从路由事件处理程序中移除路由事件
    remove { RemoveHandler(ControlLoadOverEvent, value); }
    }

    }

    2 使用并绑定自定义控件的事件

    <!--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


    public DelegateCommand<Object> ButtonLoadOverCommand { get; set; }
    public void ButtonLoadOver(Object obj)
    {
    //这里的参数为自定义控件对象
    ExtButton btn = obj as ExtButton;
    if (btn != null)
    {
    var content = btn.Content;
    }
    }
    方式2


    this.extButton.ControlLoadOver += ExtButton_ControlLoadOver;

    private void ExtButton_ControlLoadOver(object sender, RoutedEventArgs e)
    {
    var btn = (Button)e.Source;
    var str = btn.Content;
    }

  • 相关阅读:
    使用 richtextbox 输出程序运行信息
    多线程 更新 winform 控件的值,以避免UI线程的卡顿
    多线程 以及 主程序退出时 子线程的销毁
    supersocket 通过配置文件启动服务 总是 初始化失败的 解决办法
    增删改存储过程 框架
    winform DataGridView 通用初始化
    SQLServer存储过程 实例,很多语法可以以后参考
    Winform中 DataGridView控件中的 CheckBox 的值读出来 始终 为 False ,已解决
    winform中 让 程序 自己重启
    字符数组什么时候要加‘’
  • 原文地址:https://www.cnblogs.com/robertyao/p/8093527.html
Copyright © 2011-2022 走看看