WPF自定义控件步骤

让人想犯罪 __ 提交于 2019-12-09 04:03:59

1 .在类库里面添加system.xaml的引用,给控件指定Name;

2.设计控件的外观,并将内部元素绑定到控件类的属性;此时即使没有在类中增加相关属性也不会报错,xaml类似html错误只是不显示而已;

3.定义静态的依赖项;

4.定义依赖项的包装属性;

5.在静态构造函数中注册依赖项属性,注意设置回调函数;

6.实现回调函数

7 定义路由事件并注册

8.定义路由事件的包装器

9.触发路由事件

<UserControl x:Class="CustomControls.ColorPickerUserControl"
             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:CustomControls"
             mc:Ignorable="d"
             Name="ColorPicker" Height="70" Width="285">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Slider Grid.Row="0" Grid.Column="0" Margin="{Binding ElementName=ColorPicker,Path=Padding}" 
                Minimum="0" Maximum="255" Value="{Binding ElementName=ColorPicker,Path=Red}"
                VerticalAlignment="Center"></Slider>

        <Slider Grid.Row="1" Grid.Column="0" Margin="{Binding ElementName=ColorPicker,Path=Padding}" 
                Minimum="0" Maximum="255" Value="{Binding ElementName=ColorPicker,Path=Green}"
                VerticalAlignment="Center"></Slider>
        <Slider Grid.Row="2" Grid.Column="0" Margin="{Binding ElementName=ColorPicker,Path=Padding}" 
                Minimum="0" Maximum="255" Value="{Binding ElementName=ColorPicker,Path=Blue}" 
                VerticalAlignment="Center"></Slider>
        <Rectangle Grid.Row="0" Grid.Column="1" Grid.RowSpan="3" Width="100" Margin="{Binding ElementName=ColorPicker,Path=Padding}"
                   Stroke="Black" StrokeThickness="1">
            <Rectangle.Fill>
                <SolidColorBrush Color="{Binding ElementName=ColorPicker,Path=Color}"></SolidColorBrush>
            </Rectangle.Fill>

        </Rectangle>
    </Grid>

</UserControl>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace CustomControls
{
    /// <summary>
    /// ColorPickerUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class ColorPickerUserControl : UserControl
    {
        public ColorPickerUserControl()
        {
            InitializeComponent();
        }


        public static DependencyProperty ColorProperty;
        public Color Color
        {
            get
            {
                return (Color)GetValue(ColorProperty);
            }
            set
            {
                SetValue(ColorProperty, value);
            }
        }



        public static DependencyProperty RedProperty;
        public byte Red
        {
            get
            {
                return (byte)GetValue(RedProperty);
            }
            set
            {
                SetValue(RedProperty, value);
            }
        }



        public static DependencyProperty GreenProperty;
        public byte Green
        {
            get
            {
                return (byte)GetValue(GreenProperty);
            }
            set
            {
                SetValue(GreenProperty, value);
            }
        }



        public static DependencyProperty BlueProperty;
        public byte Blue
        {
            get
            {
                return (byte)GetValue(BlueProperty);
            }
            set
            {
                SetValue(BlueProperty, value);
            }
        }


        static ColorPickerUserControl()
        {
            ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(ColorPickerUserControl), 
                new PropertyMetadata(Colors.Black, new PropertyChangedCallback(OnColorChanged)));
            RedProperty = DependencyProperty.Register("Red", typeof(byte), typeof(ColorPickerUserControl),
                new PropertyMetadata((byte)0, new PropertyChangedCallback(OnRGBChanged)));
            GreenProperty = DependencyProperty.Register("Green", typeof(byte), typeof(ColorPickerUserControl),
                new PropertyMetadata((byte)0, new PropertyChangedCallback(OnRGBChanged)));
            BlueProperty = DependencyProperty.Register("Blue", typeof(byte), typeof(ColorPickerUserControl),
                new PropertyMetadata((byte)0, new PropertyChangedCallback(OnRGBChanged)));
        }



        private static void OnRGBChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ColorPickerUserControl colorPicker = (ColorPickerUserControl)d;
            Color color = colorPicker.Color;
            if (e.Property == RedProperty)
            {
                color.R = (byte)e.NewValue;
            }
            else if (e.Property == GreenProperty)
            {
                color.G = (byte)e.NewValue;
            }
            else
            {
                color.B= (byte)e.NewValue;
            }
            colorPicker.Color = color;

        }


        private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ColorPickerUserControl colorPicker = (ColorPickerUserControl)d;
            Color newColor = (Color)e.NewValue;
            colorPicker.Red = newColor.R;
            colorPicker.Green = newColor.G;
            colorPicker.Blue = newColor.B;
            Color oldColor = (Color)e.OldValue;
            RoutedPropertyChangedEventArgs<Color> args = new RoutedPropertyChangedEventArgs<Color>(oldColor,newColor);
            args.RoutedEvent = ColorChangedEvent;
            colorPicker.RaiseEvent(args);

        }


        public static readonly RoutedEvent ColorChangedEvent = EventManager.RegisterRoutedEvent("ColorChanged", RoutingStrategy.Bubble, 
            typeof(RoutedPropertyChangedEventHandler<Color>), typeof(ColorPickerUserControl));
        public event RoutedPropertyChangedEventHandler<Color> ColorChanged
        {
            add
            {
                AddHandler(ColorChangedEvent, value);
            }
            remove
            {
                RemoveHandler(ColorChangedEvent, value);
            }

        }


    }

}



<Window x:Class="CustomControlDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CustomControlDemo"
        xmlns:lib ="clr-namespace:CustomControls;assembly=CustomControls"
        mc:Ignorable="d"
        Title="MainWindow" Height="309.6" Width="348.2">
    <Grid>
        <StackPanel>
            <TextBlock Name="tbColor" Margin="3">111</TextBlock>//放在usercontrol前面否则设置color时候会报错

            <lib:ColorPickerUserControl Name="colorPicker" Height="Auto" Width="Auto" Margin="3" Padding="3" Color="Red"
                                    ColorChanged="ColorPickerUserControl_ColorChanged"></lib:ColorPickerUserControl>

        </StackPanel>
        
    </Grid>

</Window>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace CustomControlDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }


        private void ColorPickerUserControl_ColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
        {
            Color color = (Color)e.NewValue;
            tbColor.Text = "The new Color is" + color.ToString();
        }
    }
}

转载于:https://www.cnblogs.com/dxmfans/p/9434825.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!