自定义控件CustomControl中依赖属性、命令的使用
C#:
1 public class CustomControl1 : Control 2 { 3 public static readonly DependencyProperty BackgroProperty = 4 DependencyProperty.Register("Backgro", typeof(Brush), typeof(CustomControl1)); 5 6 public Brush Backgro 7 { 8 get { return (Brush)GetValue(BackgroProperty); } 9 set { SetValue(BackgroProperty, value); } 10 } 11 12 static CustomControl1() 13 { 14 DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1))); 15 InitializeCommand(); 16 } 17 18 public override void OnApplyTemplate() 19 { 20 base.OnApplyTemplate(); 21 Backgro = Brushes.Red; 22 } 23 24 private static RoutedCommand bgChangeCmd; 25 public static RoutedCommand BgChangeCmd 26 { 27 get { return bgChangeCmd; } 28 } 29 30 private static void InitializeCommand() 31 { 32 bgChangeCmd = new RoutedCommand("BgChangeCmd",typeof(CustomControl1)); 33 CommandManager.RegisterClassCommandBinding(typeof(CustomControl1), new CommandBinding(bgChangeCmd, OnBgChangeCmd)); 34 CommandManager.RegisterClassInputBinding(typeof(CustomControl1), new InputBinding(bgChangeCmd, new KeyGesture(Key.Up))); 35 } 36 37 private static void OnBgChangeCmd(object sender, ExecutedRoutedEventArgs e) 38 { 39 CustomControl1 control = sender as CustomControl1; 40 if (control != null) 41 { 42 control.OnBgChange(); 43 } 44 } 45 46 protected virtual void OnBgChange() 47 { 48 if (Backgro == Brushes.Red) 49 { 50 Backgro = Brushes.Green; 51 } 52 else if (Backgro == Brushes.Green) 53 { 54 Backgro = Brushes.Blue; 55 } 56 else 57 { 58 Backgro = Brushes.Red; 59 } 60 } 61 }
Xaml:
1 <ResourceDictionary 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:local="clr-namespace:WpfApplication3"> 5 6 <Style TargetType="{x:Type local:CustomControl1}"> 7 <Setter Property="Template"> 8 <Setter.Value> 9 <ControlTemplate TargetType="{x:Type local:CustomControl1}"> 10 <Button Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl1}}, Path=Backgro}" 11 Command="{x:Static local:CustomControl1.BgChangeCmd}" 12 BorderBrush="Black" BorderThickness="1"> 13 <Button.Style> 14 <Style TargetType="Button"> 15 <Setter Property="Template"> 16 <Setter.Value> 17 <ControlTemplate TargetType="Button"> 18 <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> 19 <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> 20 </Border> 21 </ControlTemplate> 22 </Setter.Value> 23 </Setter> 24 </Style> 25 </Button.Style> 26 </Button> 27 </ControlTemplate> 28 </Setter.Value> 29 </Setter> 30 </Style> 31 </ResourceDictionary>