• WPF自定义控件


    一、添加WPF自定义控件库(Framework/Core)

    删除掉创建类库时自带的类,以及Generic.xml文件下该控件对应的style代码(纯个人习惯)

    二、类库中添加自己的自定义控件

    以圆角矩形按钮为例:

    类库项目新建自定义控件

    public class MyButton : Button
        {
            static MyButton()
            {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(MyButton), new FrameworkPropertyMetadata(typeof(MyButton)));
            }
        }
    

    可添加自身属性、依赖属性来拓展该控件功能,供控件使用者使用。

    Generic.xml下添加代码片段,改变button样式和模板

        <Style TargetType="{x:Type local:MyButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:MyButton}">
                        <Border Name="bd" CornerRadius="10" Background="{TemplateBinding Background}"
                                BorderThickness="1" BorderBrush="Black">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    其中Border的背景一定要加,不然按钮除了中间位置,其它位置不能响应点击事件。

    当项目中自定义控件很多时,可单独为控件定义xaml文件,在Generic.xml文件中统一调用。

    使用的话,引用添加项目引用选择自己添加的自定义控件类库。

    <Window x:Class="TestWPF.MainWindow"
            xmlns:MyNamespace="clr-namespace:ControlLibrary;assembly=ControlLibrary"
            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:TestWPF"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800" Name="mainWindow">
        <Grid>
            <MyNamespace:MyButton Background="Transparent" Width="80" Height="60" Content="按钮" Click="MyButton_Click"/>
        </Grid>
    </Window>

    效果如图:

    本文主要在过程,其它方面并不具体涉及,例如做一个分页控件,其模板可由一个grid下各个按钮构成,其类属性由页数,当前行数等构成,对外暴露的依赖属性可由数据个数等等

  • 相关阅读:
    Guard Towers (二分图+二分答案,曼儿哈顿举例—》转化成切比雪夫距离》进而用图形解决)
    CentOS镜像下载
    Envoy 是专为大型现代 SOA(面向服务架构)架构设计的 L7 代理和通信总线
    什么要做分库分表?
    SQL 军规到底能不能用 join
    算法维特比和隐马尔可夫模型
    微前端开发
    vue2多页面应用系统
    Abp Vnext Vue3
    巨无霸项目的存在的问题
  • 原文地址:https://www.cnblogs.com/jingjingweixiao/p/14450836.html
Copyright © 2020-2023  润新知