天天看點

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