WPF UserControl 的绑定事件、属性、附加属性

原文: WPF UserControl 的绑定事件、属性、附加属性

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Vblegend_2013/article/details/83477473

WPF UserControl里可供绑定的属性

        /// <summary>
        /// 重写基类 Margin
        /// </summary>
        public new Thickness Margin
        {
            get { return (Thickness)GetValue(MarginProperty); }
            set { SetValue(MarginProperty, value); }
        }
        public new static readonly DependencyProperty MarginProperty = DependencyProperty.Register("Margin", typeof(Thickness), typeof(MirrorGrid), new FrameworkPropertyMetadata(new Thickness(0), new PropertyChangedCallback(OnMarginChanged)));
        private static void OnMarginChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            ((FrameworkElement)target).Margin = (Thickness)e.NewValue;
        }

UserControl 里的事件路由

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

路由事件


        private void RoutedToolTipShow(RoutedEventArgs param)
        {
            param.RoutedEvent = OnToolTipShowEvent;
            param.Source = this;
            this.RaiseEvent(param);
        }

控件附加属性

  public abstract class AquariumServices : DependencyObject
    {
        public enum Bouyancy {Floats,Sinks,Drifts}

        public static readonly DependencyProperty BouyancyProperty = DependencyProperty.RegisterAttached(
          "Bouyancy",
          typeof(Bouyancy),
          typeof(AquariumServices),
          new PropertyMetadata(Bouyancy.Floats)
        );
        public static void SetBouyancy(DependencyObject element, Bouyancy value)
        {
            element.SetValue(BouyancyProperty, value);
        }
        public static Bouyancy GetBouyancy(DependencyObject element)
        {
            return (Bouyancy)element.GetValue(BouyancyProperty);
        }
    }

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9941908.html