欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-08 22:23:56
...

 

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);
        }
    }