1. 程式人生 > >WPF UserControl 的繫結事件、屬性、附加屬性

WPF UserControl 的繫結事件、屬性、附加屬性

原文: WPF UserControl 的繫結事件、屬性、附加屬性

 

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