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下各个按钮构成,其类属性由页数,当前行数等构成,对外暴露的依赖属性可由数据个数等等

posted @ 2021-02-26 10:12  静静微笑  阅读(1099)  评论(0编辑  收藏  举报