WPF 給用戶控件增加自定義事件的記錄


第一步 在自定義控件里加上聲明

        /// <summary>
        /// The click event
        /// </summary>
        public static readonly RoutedEvent userControlClickEvent = EventManager.RegisterRoutedEvent("UserControlClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CommonButton));

        /// <summary>
        /// 控件點擊的操作.
        /// </summary>
        public event RoutedEventHandler UserControlClick
        {
            add
            {
                AddHandler(userControlClickEvent, value);
            }

            remove
            {
                RemoveHandler(userControlClickEvent, value);
            }
        }

第二步 給自定義控件的按鈕的click里添加調用

        public void btnClick(object sender, RoutedEventArgs e)
        {
            RoutedEventArgs args = new RoutedEventArgs(userControlClickEvent, this);
            RaiseEvent(args);
        }

第三步 外部調用該事件

            CommonButton button = new CommonButton();
            button.UserControlClick += Button_UserControlClick;
            button.Width = 200;
            button.Height = 200;
            button.ImagePathNormal = "/Images/LeftMenuButtons/left_menu_1_normal.png";
            button.ImagePathPressed = "/Images/LeftMenuButtons/left_menu_1_selected.png";
            button.SetValue(Canvas.ZIndexProperty, 999);
            button.SetValue(Canvas.LeftProperty, (double)0);
            button.SetValue(Canvas.TopProperty, (double)0);

            mainCanvas.Children.Add(button);
        private void Button_UserControlClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("已執行");
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM