WPF编程宝典P18----ColorPicker 和FlipPanel的讲解

摘要:
1、 ColorPicker的实现1,自定义属性#regionColorPickOftheBook[TemplatePart(名称=“PART_RedSlider”,类型=typeof(RangeBase)][TemplatePart(名称=”PART_BlueSlider“,类型=typeof(Range Base))][TTemplatePart(名称“PART_GreenS

一,ColorPicker的实现

1,自定义属性

  #region ColorPick Of the Book
    [TemplatePart(Name = "PART_RedSlider", Type = typeof(RangeBase))]
    [TemplatePart(Name = "PART_BlueSlider", Type = typeof(RangeBase))]
    [TemplatePart(Name = "PART_GreenSlider", Type = typeof(RangeBase))]
    [TemplatePart(Name = "PART_PreviewBrush", Type = typeof(SolidColorBrush))]

自定义依赖项属性(propdp模板快速定义)

public static DependencyProperty ColorProperty;
public static DependencyProperty RedProperty;
public static DependencyProperty GreenProperty;
public static DependencyProperty BlueProperty;
static ColorPicker()        {            //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.            //This style is defined in themesgeneric.xaml            DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorPicker), new FrameworkPropertyMetadata(typeof(ColorPicker)));            ColorProperty = DependencyProperty.Register("Color", typeof(Color),            typeof(ColorPicker),            new FrameworkPropertyMetadata(new PropertyChangedCallback(OnColorChanged)));            RedProperty = DependencyProperty.Register("Red", typeof(byte),                typeof(ColorPicker),                new FrameworkPropertyMetadata(new PropertyChangedCallback(OnColorRGBChanged)));            GreenProperty = DependencyProperty.Register("Green", typeof(byte),                typeof(ColorPicker),                    new FrameworkPropertyMetadata(new PropertyChangedCallback(OnColorRGBChanged)));            BlueProperty = DependencyProperty.Register("Blue", typeof(byte),                typeof(ColorPicker),                new FrameworkPropertyMetadata(new PropertyChangedCallback(OnColorRGBChanged)));        }

DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorPicker), new FrameworkPropertyMetadata(typeof(ColorPicker))); 用来在themes/generic.xaml中定义默认模板.


2,自定义Command

// Set up command bindings.         CommandBinding binding = new CommandBinding(ApplicationCommands.Undo,          UndoCommand_Executed, UndoCommand_CanExecute);         this.CommandBindings.Add(binding);


private Color? previousColor;        private void UndoCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)        {            e.CanExecute = previousColor.HasValue;        }        private void UndoCommand_Executed(object sender, ExecutedRoutedEventArgs e)        {            // Use simple reverse-or-redo Undo (like Notepad).            this.Color = (Color)previousColor;        }

3,进行触发的颜色变更的跟踪

 private static void OnColorChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ColorPicker colorPicker = (ColorPicker)sender;

            Color oldColor = (Color)e.OldValue;
            Color newColor = (Color)e.NewValue;
            colorPicker.Red = newColor.R;
            colorPicker.Green = newColor.G;
            colorPicker.Blue = newColor.B;

            colorPicker.previousColor = oldColor;
            colorPicker.OnColorChanged(oldColor, newColor);
        }

        private static void OnColorRGBChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ColorPicker colorPicker = (ColorPicker)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;
        }
4

5自定义RouteEvent事件

  public static readonly RoutedEvent ColorChangedEvent =
           EventManager.RegisterRoutedEvent("ColorChanged", RoutingStrategy.Bubble,
               typeof(RoutedPropertyChangedEventHandler<Color>), typeof(ColorPicker));

        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 = ColorPicker.ColorChangedEvent;
            RaiseEvent(args);
        }

6,重新架构OnApply()来进行数据绑定或者别的工作

 public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            RangeBase slider = GetTemplateChild("PART_RedSlider") as RangeBase;
            if (slider != null)
            {
                Binding binding = new Binding("Red");
                binding.Source = this;
                binding.Mode = BindingMode.TwoWay;
                slider.SetBinding(RangeBase.ValueProperty, binding);
            }
            slider = GetTemplateChild("PART_GreenSlider") as RangeBase;
            if (slider != null)
            {
                Binding binding = new Binding("Green");
                binding.Source = this;
                binding.Mode = BindingMode.TwoWay;
                slider.SetBinding(RangeBase.ValueProperty, binding);
            }
            slider = GetTemplateChild("PART_BlueSlider") as RangeBase;
            if (slider != null)
            {
                Binding binding = new Binding("Blue");
                binding.Source = this;
                binding.Mode = BindingMode.TwoWay;
                slider.SetBinding(RangeBase.ValueProperty, binding);
            }

            SolidColorBrush brush = GetTemplateChild("PART_PreviewBrush") as SolidColorBrush;
            if (brush != null)
            {
                Binding binding = new Binding("Color");
                binding.Source = brush;
                binding.Mode = BindingMode.OneWayToSource;
                this.SetBinding(ColorPicker.ColorProperty, binding);
            }
        }
    }

7,默认的模板查看

 <Style TargetType="{x:Type local:ColorPicker}">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type local:ColorPicker}">
          <Border Background="{TemplateBinding Background}"
                  BorderBrush="{TemplateBinding BorderBrush}"
                  BorderThickness="{TemplateBinding BorderThickness}">
            <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 Name="PART_RedSlider" Minimum="0" Maximum="255"
                       Margin="{TemplateBinding Padding}"></Slider>
              <Slider Grid.Row="1" Name="PART_GreenSlider" Minimum="0" Maximum="255"
                       Margin="{TemplateBinding Padding}"></Slider>

              <Slider Grid.Row="2" Name="PART_BlueSlider" Minimum="0" Maximum="255"
                       Margin="{TemplateBinding Padding}"></Slider>

              <Rectangle Grid.Column="1" Grid.RowSpan="3"
                         Margin="{TemplateBinding Padding}"
                         Width="50" Stroke="Black" StrokeThickness="1">
                <Rectangle.Fill>
                  <SolidColorBrush Color="{Binding Path=Color,
                       RelativeSource={RelativeSource TemplatedParent}}"></SolidColorBrush>
                </Rectangle.Fill>
              </Rectangle>

            </Grid>

          </Border>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

免责声明:文章转载自《WPF编程宝典P18----ColorPicker 和FlipPanel的讲解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇canvas在小程序中添加图片(本地图片/网络图片),在html中添加图片c# 对unicode解码下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WPF绑定错误

listbox绑定遇到了奇怪的报错如下: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl'...

WPF 2D绘图(3)PathGeometry

PathGeometry可以创建任意的2D图形形状。 其内部通过PathSegment集合来实现 如画2个三角形 <Path Stroke="Black" StrokeThickness="1"> <Path.Data> <PathGeometry>...

WPF 多语言解决方案

1、首先安装Multilingual App Toolkit 2、新建项目,在VS中点击"工具" -> "Multilingual App Toolkit" -> "启用选定内容" 如果出现上述Issue, 打开项目AssemblyInfo.cs文件,加入如下代码片段,然后重复Step 2. [assembly: NeutralRes...

走进WPF之UI布局

一个成功的软件,离不开人性化的UI设计,如何抓住用户第一视觉,让用户产生依赖感,合适优雅的布局必不可少。本文以一些简单的小例子,简述WPF中布局面板控件的使用,仅供学习分享使用,如有不足之处,还请指正。 涉及知识点 在WPF中,关于布局面板控件,主要有以下几种: StackPanel:栈面板,可以将元素排列成一行或者一列。其特点是:每个元素各占一行或者一...

WPF Button添加图片

0、更改模板 效果: 代码: <Button x:Name="m_HelpButton"IsEnabled="True"Width="23"Height="23"Click="m_HelpButton_Click"> <Button.Template> <...

wpf中的窗口

wpf的窗口概念。就相当于2.0中winform中一个界面而已在wpf中窗口就是一个window类。具有图形界面这个窗口具有丰富的属性来设置自己的显示样式和外观窗口也有自己的生命周期,如图 不同的周期有不同的事件和方法可以处理很多事情。窗口激活就开始加载,然后是内容呈现。关闭窗口的时候会先引发closeing事件,在这个事件中可以阻止关闭事件进行其他处理或...