详解WPF中用户控件和自定义控件的使用

作者:步、步、为营 时间:2023-07-25 12:20:26 

介绍

无论是在WPF中还是WinForm中,都有用户控件(UserControl)和自定义控件(CustomControl),这两种控件都是对已有控件的封装,实现功能重用。但是两者还是有一些区别,本文对这两种控件进行讲解。

1.用户控件

  • 注重复合控件的使用,也就是多个现有控件组成一个可复用的控件组

  • XAML和后台代码组成,绑定紧密

  • 不支持模板重写

  • 继承自UserControl

2.自定义控件

  • 完全自己实现一个控件,如继承现有控件进行功能扩展,并添加新功能

  • 后台代码和Generic.xaml进行组合

  • 在使用时支持模板重写

  • 继承自Control

用户控件

用户控件比较容易理解,与常见的WPF窗体类似,值得注意一点的地方是内部在使用绑定的时候,需要使用RelativeSource的方式来绑定,以实现良好的封装。一个简单的案例:

定义用户控件

<UserControl
   x:Class="WpfApp19.UserControl1"
   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:local="clr-namespace:WpfApp19"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   d:DesignHeight="450"
   d:DesignWidth="800"
   mc:Ignorable="d">
   <Grid>
       <!--下面绑定都要用RelativeSource作为源-->
       <StackPanel>
           <TextBox
               Width="100"
               BorderThickness="2"
               Text="{Binding value, RelativeSource={RelativeSource AncestorType=UserControl}}" />
           <Button
               Width="100"
               Command="{Binding Command, RelativeSource={RelativeSource AncestorType=UserControl}}"
               Content="Ok" />
       </StackPanel>
   </Grid>
</UserControl>

后台代码

//根据需要定义依赖属性
//所需要绑定的值
public int value
{
    get { return (int)GetValue(valueProperty); }
    set { SetValue(valueProperty, value); }
}
public static readonly DependencyProperty valueProperty =
    DependencyProperty.Register("value", typeof(int), typeof(UserControl1), new PropertyMetadata(0));

//所需要绑定的命令
public ICommand Command
{
    get { return (ICommand)GetValue(CommandProperty); }
    set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
    DependencyProperty.Register("Command", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(default(ICommand)));

//所需要绑定的命令参数
public object CommandParemeter
{
    get { return (object)GetValue(CommandParemeterProperty); }
    set { SetValue(CommandParemeterProperty, value); }
}
public static readonly DependencyProperty CommandParemeterProperty =
    DependencyProperty.Register("CommandParemeter", typeof(object), typeof(UserControl1), new PropertyMetadata(0));

使用用户控件

<Window x:Class="WpfApp19.MainWindow"
       ...
       xmlns:local="clr-namespace:WpfApp19"
       Title="MainWindow" Height="450" Width="800">
   <Grid>
       <local:UserControl1 value="{Binding }" Command="{Binding }"/>
   </Grid>
</Window>

自定义控件

点击添加自定义控件后,会增加一个CustomControl1.cs文件以及一个Themes目录,在该目录下有一个Generic.xaml文件,该文件就是自定义控件的style。我们经常针对某些控件进行编辑模板-创建副本的操作而产生的style,其实就是Generic.xaml中定义的style。另外,有时我们可能遇到一种情况,也就是相同的软件在不同的Windows版本下运行,表现形式可能会不同,甚至某些系统下运行不了,这就是和不同系统下的默认的Theme不同。其实wpf控件找不到自定义的样式时,会从系统获取样式,查找顺序是,先查找所在的程序集,如果程序集定义了ThemeInfo特性,那么会查看ThemeInfoDictionaryLocation的属性值,该属性如果是None则说明没有特定的主题资源,值为SourceAssembly,说明特定资源定义在程序集内部,值为ExternalAssembly则说明在外部,如果还是没有找到,则程序会在自身的themes/generic.xaml中获取,在generic.xaml中获取的其实就和系统默认样式相关。

不同xaml所对应的系统主题

详解WPF中用户控件和自定义控件的使用

按钮案例

详解WPF中用户控件和自定义控件的使用

C#文件

public class Switch : ToggleButton
{
   static Switch()
   {
       //通过重写Metadata,控件就会通过程序集themes文件夹下的generic.xaml来寻找系统默认样式
       DefaultStyleKeyProperty.OverrideMetadata(typeof(Switch), new FrameworkPropertyMetadata(typeof(Switch)));
   }
}

Themes文件夹下的Generic.xaml文件

注意在该文件中不能有中文,注释也不行

<Style TargetType="{x:Type local:Switch}">
   <Setter Property="Template">
       <Setter.Value>
           <ControlTemplate TargetType="{x:Type local:Switch}">
               <Grid>
                   <Border
                       Name="dropdown"
                       Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                       Margin="-23"
                       CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                       Visibility="Collapsed">
                       <Border.Background>
                           <RadialGradientBrush>
                               <GradientStop Offset="1" Color="Transparent" />
                               <GradientStop Offset="0.7" Color="#5500D787" />
                               <GradientStop Offset="0.59" Color="Transparent" />
                           </RadialGradientBrush>
                       </Border.Background>
                   </Border>
                   <Border
                       Name="bor"
                       Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                       Background="Gray"
                       BorderBrush="DarkGreen"
                       BorderThickness="5"
                       CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}">
                       <Border
                           Name="bor1"
                           Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
                           Margin="2"
                           Background="#FF00C88C"
                           CornerRadius="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" />
                   </Border>
               </Grid>
               <ControlTemplate.Triggers>
                   <Trigger Property="IsChecked" Value="True">
                       <Trigger.EnterActions>
                           <BeginStoryboard>
                               <Storyboard>
                                   <ColorAnimation
                                       Storyboard.TargetName="bor1"
                                       Storyboard.TargetProperty="Background.Color"
                                       To="White"
                                       Duration="0:0:0.5" />
                                   <ColorAnimation
                                       Storyboard.TargetName="bor"
                                       Storyboard.TargetProperty="BorderBrush.Color"
                                       To="#FF32FAC8"
                                       Duration="0:0:0.5" />
                                   <ObjectAnimationUsingKeyFrames Storyboard.TargetName="dropdown" Storyboard.TargetProperty="Visibil
                                       <DiscreteObjectKeyFrame KeyTime="0:0:0.3">
                                           <DiscreteObjectKeyFrame.Value>
                                               <Visibility>Visible</Visibility>
                                           </DiscreteObjectKeyFrame.Value>
                                       </DiscreteObjectKeyFrame>
                                   </ObjectAnimationUsingKeyFrames>
                               </Storyboard>
                           </BeginStoryboard>
                       </Trigger.EnterActions>
                       <Trigger.ExitActions>
                           <BeginStoryboard>
                               <Storyboard>
                                   <ColorAnimation Storyboard.TargetName="bor1" Storyboard.TargetProperty="Background.Color" />
                                   <ColorAnimation Storyboard.TargetName="bor" Storyboard.TargetProperty="BorderBrush.Color" />
                                   <ObjectAnimationUsingKeyFrames Storyboard.TargetName="dropdown" Storyboard.TargetProperty="Visibil
                                       <DiscreteObjectKeyFrame KeyTime="0:0:0.3">
                                           <DiscreteObjectKeyFrame.Value>
                                               <Visibility>Collapsed</Visibility>
                                           </DiscreteObjectKeyFrame.Value>
                                       </DiscreteObjectKeyFrame>
                                   </ObjectAnimationUsingKeyFrames>
                               </Storyboard>
                           </BeginStoryboard>
                       </Trigger.ExitActions>
                   </Trigger>
               </ControlTemplate.Triggers>
           </ControlTemplate>
       </Setter.Value>
   </Setter>
</Style>

使用自定控件

<Grid>
   <local:Switch Width="100" Height="100" />
</Grid>

自定义控件中常用的知识点

TemplatePart特性

在自定义控件中,有些控件是需要有名称的以便于调用,如在重写的OnApplyTemplate()方法中得到指定的button。这就要求用户在使用控件时,不能够修改模板中的名称。

//应用该控件时调用
public override void OnApplyTemplate()
{
   UpButtonElement = GetTemplateChild("UpButton") as RepeatButton;
   DownButtonElement = GetTemplateChild("DownButton") as RepeatButton;
}

所以在类前面使用特性进行标注

[TemplatePart(Name = "UpButton", Type = typeof(RepeatButton))]
[TemplatePart(Name = "DownButton", Type = typeof(RepeatButton))]
public class Numeric : Control{}

视觉状态的定义与调用

自定义控件中可以定义视觉状态来呈现不同状态下的效果。

在xml中定义视觉状态,不同组下的视觉状态是互斥的

<VisualStateManager.VisualStateGroups>
   <VisualStateGroup Name="FocusStates">
       <VisualState Name="Focused">
           <Storyboard>
               <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusVisual"
                          Storyboard.TargetProperty="Visibility" Duration="0">
                   <DiscreteObjectKeyFrame KeyTime="0">
                       <DiscreteObjectKeyFrame.Value>
                           <Visibility>Visible</Visibility>
                       </DiscreteObjectKeyFrame.Value>
                   </DiscreteObjectKeyFrame>
               </ObjectAnimationUsingKeyFrames>
           </Storyboard>
       </VisualState>
       <VisualState Name="Unfocused"/>
   </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

在C#中对应视觉状态的切换

private void UpdateStates(bool useTransitions)
{
   if (IsFocused)
   {
       VisualStateManager.GoToState(this, "Focused", false);
   }
   else
   {
       VisualStateManager.GoToState(this, "Unfocused", false);
   }
}

同时可以在后台类中使用特性来标注

[TemplateVisualState(Name = "Focused", GroupName = "FocusedStates")]
[TemplateVisualState(Name = "Unfocused", GroupName = "FocusedStates")]
public class Numeric : Control{}

其实完全可以使用Trigger来实现该功能

来源:https://www.cnblogs.com/qsnn/p/17102469.html

标签:WPF,用户,自定义,控件
0
投稿

猜你喜欢

  • Java毕业设计实战之线上水果超市商城的实现

    2021-09-15 19:23:01
  • java中计算字符串长度的方法及u4E00与u9FBB的认识

    2022-07-15 18:28:20
  • spring mvc4的日期/数字格式化、枚举转换示例

    2021-11-07 09:49:11
  • C# 抽象类,抽象属性,抽象方法(实例讲解)

    2022-03-14 09:22:16
  • Android 自定义View实现抽屉效果

    2022-08-03 01:27:00
  • Java基础之Stream流原理与用法详解

    2021-06-07 22:16:05
  • 深入解析java中的locale

    2023-11-09 18:14:20
  • WheelPicker自定义时间选择器控件

    2023-05-16 18:30:05
  • c# mutex互斥量的深入解析

    2022-03-13 02:38:42
  • android scrollview 滑动到顶端或者指定位置的实现方法

    2022-04-27 00:12:40
  • Java NIO框架Netty简单使用的示例

    2022-09-08 02:51:27
  • Java图片裁剪和生成缩略图的实例方法

    2023-11-09 00:01:50
  • unity实现鼠标跟随(ITween)

    2021-09-26 00:01:43
  • C#实现语音播报功能

    2023-06-26 20:35:26
  • Kryo框架使用方法代码示例

    2021-05-30 15:46:05
  • Unity Shader实现黑幕过场效果

    2022-01-13 00:18:10
  • 浅谈一下Servlet的定义以及运行原理

    2023-08-14 10:50:07
  • 利用源码编译Android系统的APK和可执行命令的方法

    2023-12-22 13:09:46
  • MAC下如何设置JDK环境变量

    2023-12-20 16:05:24
  • Android studio 出现错误Run with --stacktrace option to get the stack trace. Run with --info or --debu

    2022-10-25 09:43:15
  • asp之家 软件编程 m.aspxhome.com