天天看點

WPF之自定義使用者控件

C#代碼:

public partial class WPFUserControl : UserControl
    {
        public WPFUserControl()
        {
            InitializeComponent();
        }

        //定義依賴項屬性
        public static DependencyProperty ColorProperty;
        public static DependencyProperty RedProperty;
        public static DependencyProperty GreenProperty;
        public static DependencyProperty BlueProperty;
        static WPFUserControl()
        {
            //注冊依賴項屬性
            ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(WPFUserControl), new PropertyMetadata(Colors.Black, new PropertyChangedCallback(OnColorChanged)));
            //DependencyProperty.Register(屬性名稱,屬性類型,所屬控件類型,注冊依賴屬性)
            //PropertyMetadata(預設值, PropertyChangedCallback更改時的回調函數)

            RedProperty = DependencyProperty.Register("Red", typeof(byte), typeof(WPFUserControl), new PropertyMetadata( new PropertyChangedCallback(OnColorRGBChanged)));
            BlueProperty = DependencyProperty.Register("Blue", typeof(byte), typeof(WPFUserControl), new PropertyMetadata( new PropertyChangedCallback(OnColorRGBChanged)));
            GreenProperty = DependencyProperty.Register("Green", typeof(byte), typeof(WPFUserControl), new PropertyMetadata( new PropertyChangedCallback(OnColorRGBChanged)));
        }
        //聲明屬性
        public Color Color
        {
            get { return (Color)GetValue(ColorProperty); }
            set { SetValue(ColorProperty, value); }
        }
        public byte Red
        {
            get { return (byte)GetValue(RedProperty); }
            set { SetValue(RedProperty, value); }
        }
        public byte Blue
        {
            get { return (byte)GetValue(BlueProperty); }
            set { SetValue(BlueProperty, value); }
        }
        public byte Green
        {
            get { return (byte)GetValue(GreenProperty); }
            set { SetValue(GreenProperty, value); }
        }
        //聲明回調函數方法
        private static void OnColorRGBChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            WPFUserControl colorPicker = (WPFUserControl)sender;
            Color color = colorPicker.Color;
            if (e.Property == RedProperty)
            {
                color.R = (byte)e.NewValue;
            }
            else if (e.Property == GreenProperty)
            {
                color.G = (byte)e.NewValue;
            }
            else if (e.Property == BlueProperty)
            {
                color.B = (byte)e.NewValue;
            }
            colorPicker.Color = color;
        }
        //聲明回調函數方法
        private static void OnColorChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            WPFUserControl colorPicker = (WPFUserControl)sender;
            Color color = colorPicker.Color;
            Color oldColor = (Color)e.OldValue;
            Color newColor = (Color)e.NewValue;
            colorPicker.Red = newColor.R;
            colorPicker.Green = newColor.G;
            colorPicker.Blue = newColor.B;
            colorPicker.OnColorChanged(oldColor,newColor);
        }
        //注冊路由事件
        private static readonly RoutedEvent ColorChangedEvent = EventManager.RegisterRoutedEvent("ColorChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<Color>), typeof(WPFUserControl));

        //RoutedEvent:表示和辨別路由事件,并聲明其特征。
        //EventManager類:提供事件相關的實用工具方法,這些方法可為類所有者注冊路由事件,并添加類處理程式。
        //EventManager.RegisterRoutedEvent方法:向 Windows Presentation Foundation (WPF) 事件系統注冊新的路由事件
        //EventManager.RegisterRoutedEvent(路由事件的名稱,RoutingStrategy路由政策,事件處理程式的類型,路由事件的所有者類類型)
        //RoutedPropertyChangedEventHandler<T>:表示将處理跟蹤屬性值更改的各個路由事件的方法。

        //聲明事件
        public event RoutedPropertyChangedEventHandler<Color> ColorChanged
        {
            add { AddHandler(ColorChangedEvent, value); }  
            //為指定的路由事件添加路由事件處理程式,并将該處理程式添加到目前元素的處理程式集合中。
            remove { RemoveHandler(ColorChangedEvent, value); } 
            //從此元素中删除指定的路由事件處理程式。
        }

        //事件引發
        private void OnColorChanged(Color oldValue, Color newValue)
        {
            RoutedPropertyChangedEventArgs<Color> args = new RoutedPropertyChangedEventArgs<Color>(oldValue,newValue);
            args.RoutedEvent = WPFUserControl.ColorChangedEvent;
            UIElement.RaiseEvent(args);//繼承引發事件
            //RoutedPropertyChangedEventArgs<T> 類:提供有關依賴屬性值更改的資料(由特定的路由事件報告),其中包含發生更改的屬性的舊值和新值。
            //RaiseEvent:擷取或設定與此 RoutedEventArgs 執行個體關聯的 RoutedEvent。
            //RoutedEventArgs 類:包含與路由事件相關聯的狀态資訊和事件資料。
            //RaiseEvent:引發特定路由事件。 在提供的 RoutedEventArgs 執行個體内辨別将引發的 RoutedEvent(作為該事件資料的 RoutedEvent 屬性)。
        }
    }
           

Xaml代碼

<UserControl x:Class="wpf.WPFUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:wpf"
             Name="colorPicker">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>
        <Slider Name="SliderRed" Minimum="0" Maximum="255" Margin="{Binding ElementName=colorPicker,Path=Padding}" Value="{Binding ElementName=colorPicker,Path=Red}"></Slider>
        <Slider Name="SliderGreen"  Grid.Row="1" Minimum="0" Maximum="255" Margin="{Binding ElementName=colorPicker,Path=Padding}" Value="{Binding ElementName=colorPicker,Path=Green}"></Slider>
        <Slider Name="SliderBlue"  Grid.Row="2" Minimum="0" Maximum="255" Margin="{Binding ElementName=colorPicker,Path=Padding}" Value="{Binding ElementName=colorPicker,Path=Blue}"></Slider>
        <Rectangle Grid.Column="1" Grid.RowSpan="3" Margin="{Binding ElementName=colorPicker,Path=Padding}" Width="50" Stroke="Black" StrokeThickness="1">
            <Rectangle.Fill>
                <SolidColorBrush Color="{Binding ElementName=colorPicker,Path=Color}"/>
            </Rectangle.Fill>

        </Rectangle> 
    </Grid>
</UserControl>
           
WPF

繼續閱讀