WPF中用户控件和自定义控件

这篇具有很好参考价值的文章主要介绍了WPF中用户控件和自定义控件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

WPF中用户控件和自定义控件

无论是在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,wpf,c#,.net,xaml,ui

按钮案例

wpf用户控件和自定义控件,WPF,wpf,c#,.net,xaml,ui

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>

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

  1. 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{}
  1. 视觉状态的定义与调用

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

在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来实现该功能

案例学习源码下载

分享几个用户控件和自定义控件的案例,效果如下:

wpf用户控件和自定义控件,WPF,wpf,c#,.net,xaml,ui

源码下载文章来源地址https://www.toymoban.com/news/detail-811071.html

到了这里,关于WPF中用户控件和自定义控件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 进一步了解WPF UI 实现XAML语法

    Extensible Application Markup Language (XAML) 是一种用于声明性应用程序编程的标记语言。 Windows Presentation Foundation (WPF) 实现 XAML 处理器实现并提供 XAML 语言支持。 WPF 类型的实现为 XAML 表示提供了必要的类型支持,从而确保了顺畅的集成和高效的运行。 在 XAML 标记中创建 WPF 应用程序

    2024年02月02日
    浏览(30)
  • 循序渐进介绍基于CommunityToolkit.Mvvm 和HandyControl的WPF应用端开发(3)--自定义用户控件

    在我们创建界面元素的时候,不管在Vue3+ElementPlus的前端上,还是Winform桌面端上,都是会利用自定义用户控件来快速重用一些自定义的界面内容,对自定义用户控件的封装处理,也是我们开发WPF应用需要熟悉的一环。本篇随笔继续深入介绍介绍基于CommunityToolkit.Mvvm 和HandyCont

    2024年02月09日
    浏览(47)
  • WPF .Net6框架下, 使用 Microsoft.Xaml.Behaviors.Wpf 的Interaction.Triggers特性,实现ComboBox 在展开时,触发刷新列表内容的动作

    ComboBox 在WPF中是常见的控件。 一般情况下,在绑定好数据源后,其内容是固定的。 当然,你也可以实时刷新,但这将带来较高的资源消耗。 因此有个折中的办法: 只在它在展开时,自动更新列表内容。 当前文章基于 .Net6框架,其他框架不适用。 这个是用于平替winform某个组

    2024年02月09日
    浏览(49)
  • WPF 用户控件依赖注入赋值

    我一直想组件化得去开发WPF,因为我觉得将复杂问题简单化是最好的 cs部分 我将复杂的依赖注入的代码进行了优化,减少了重复内容的输入。 我现在依赖属性扩展封装在一个静态文件里面 记得UserControl.xaml里面绑定你ViewModel。这样的话有代码提示 我后面要根据Vue的单向数据

    2024年02月07日
    浏览(38)
  • WPF自定义控件

    方式一:基于现有控件进行扩展,如基于button进行扩展,UI可直接用xmal进行编辑设计,逻辑用xaml.cs进行编辑 方法二:直接创建wpf自定义控件 本文用方法二开展自定义控件!!! 1.自定义控件的内容在代码cs文件中,自定义控件继承自Control,ui界面可在Genric.xaml中定义。 2.在

    2024年02月11日
    浏览(32)
  • WPF自定义按钮控件

    在平时的WPF应用中,系统提供的按钮控件确实可以实现正常的逻辑,但是从视觉方面看的话,确实不够美观,而且每个项目的UI设计不尽相同。那么自定义按钮控件就是必须的了,网上查找了很多自定义按钮控件的办法,但每次都是写到一半就报错。在参考了多个技术贴之后

    2024年02月08日
    浏览(37)
  • 如何使用 WPF 用户控件关闭父窗口

    How to close parent windows using WPF User Control 如何使用 WPF 用户控件关闭父窗口 【问题描述】 假设有两个WPF窗口:window1和window2。 window1有一个按钮,单击此按钮将打开window2。window2包含一个用户控件。此用户控件有一个用于关闭window2的按钮。 怎样才能实现这个场景呢? 【解决方案

    2024年02月15日
    浏览(37)
  • wpf 自定义combox控件

    关键步骤 1、新建usercontrol使用基本的控件进行设计 2、依赖属性的定义,目的:外部调用时候能够使用属性进行控件样式的控制 例如 Width=\\\"200\\\" DisplayMemberPath=\\\"Name\\\" SelectedItem=\\\"{Binding SelectedItem,Mode=TwoWay}\\\" SelectionChanged=\\\"{Binding ProjectSelectCommand}\\\" CommandParameter=\\\"{Binding ElementName = Projec

    2024年02月09日
    浏览(35)
  • 【.NET深呼吸】用代码写WPF控件模板

    这一次咱们来探究一下怎么用纯代码写 WPF 模板。模板有个共同基类 FrameworkTemplate,数据模板、控件模板等是从此类派生的,因此,该类已定义了一些通用成员。 用代码构建模板,重要的成员是 VisualTree 属性,它的类型是 FrameworkElementFactory。可见,模板不是直接创建可视化

    2024年02月09日
    浏览(35)
  • wpf自定义控件-单/双箭头线

    using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace CustomControls { [TypeDescriptionProvider(typeof(CustomTypeDescriptionProvider))] public class CustomArrow : Shape { public CustomArrow () { Stroke= new SolidColorBrush(Color.FromRgb(0, 140, 206));

    2024年02月15日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包