百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

C#_WPF_按钮模板及自定义控件的使用

zhezhongyun 2025-05-03 17:51 39 浏览

源码私信联系

WPF功能强大,但是控件的用法与Winfrom不大一样。这个文件主要说明了Button控件的用法。希望能给大家一个启示。


1、按钮加入图片

        <Button Grid.Row="0" Grid.Column="0"  ToolTip="Set_Label" Name="set_label1" Height="45" VerticalAlignment="Stretch" Width="45" HorizontalAlignment="Stretch">
            <Image Source="Resources/Player1.png" StretchDirection="DownOnly" Stretch="Fill" />
        </Button>

图片的处理:

  1. 准备素材
  2. 打开Properties\Resources.resx,添加
  3. 素材属性的生成操作:Resources
  4. 引用:<Image Source="Resources/Player1.png" />

2、窗体的xaml文件中直接使用模板

        <Button  Grid.Row="0" Grid.Column="1"  x:Name="m_HelpButton" IsEnabled="True" Width="50" Height="50">
            <Button.Template>
                <ControlTemplate>
                    <Border BorderBrush="Aqua" Background="#FFEDF961">
                        <Grid>
                            <Image Margin="2" Source="Resources/Player1.png" />
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Button.Template>
        </Button>

3、使用样式

<Button Grid.Row="0" Grid.Column="2" Content="播放" Height="31"  Name="button1" Foreground="#FFDE4747" Focusable="True" BorderBrush="{x:Null}" BorderThickness="0" Style="{StaticResource ButtonLeft}" Margin="106,47,82,61"/>

App.xaml中定义样式

        <Style x:Key="ButtonLeft" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <StackPanel Orientation="Horizontal">
                            <Image Name="minBtn" Source="Resources\player0.png" />
                            <TextBlock Text="{TemplateBinding Content}" VerticalAlignment="Center" FontSize="24"></TextBlock>
                        </StackPanel>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Source" Value="Resources\player1.png" TargetName="minBtn" />
                            </Trigger>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter Property="Source" Value="Resources\pause0.png" TargetName="minBtn" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

4、鼠标覆盖变淡

        <Button Name="Add"  Margin="2"
            Grid.Row="1" Grid.Column="0"
            Style="{StaticResource Button_Menu}" Background="#FFEE2424" BorderBrush="#FF0031FF">
            <Image Source="/Resources/pause0.png" />
        </Button>

样式:

        <Style x:Key="Button_Menu" TargetType="{x:Type Button}">
            <Setter Property="Width" Value="50" />
            <Setter Property="Height" Value="50" />
            <Setter Property="BorderThickness" Value="0" />
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="MyBackgroundElement" BorderBrush="{DynamicResource ForgroundBrush}" BorderThickness="0">
                            <ContentPresenter x:Name="ButtonContentPresenter" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="MyBackgroundElement" Property="Background" Value="{DynamicResource ForgroundBrush100}"/>
                                <Setter TargetName="MyBackgroundElement" Property="Opacity" Value="0.7"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Cursor" Value="Hand" />
        </Style>

5、三态按钮及阴影效果

        <Button Grid.Row="1" Grid.Column="1" Content="button" Height="50" Width="50" RenderTransformOrigin="-4.5,-1.24">
            <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border BorderBrush="{TemplateBinding Control.BorderBrush}" BorderThickness="0" CornerRadius="3,13,3,13" Name="PART_Background">
                        <Border.Background>
                            <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                <GradientStop Color="White" Offset="0.0" />
                                <GradientStop Color="Silver" Offset="0.5" />
                                <GradientStop Color="White" Offset="0.0" />
                            </LinearGradientBrush>
                        </Border.Background>
                        <ContentPresenter Content="{TemplateBinding ContentControl.Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="UIElement.IsMouseOver" Value="True">
                            <Setter Property="Border.Background" TargetName="PART_Background">
                                <Setter.Value>
                                    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                        <GradientStop Color="Silver" Offset="0.0" />
                                        <GradientStop Color="White" Offset="0.5" />
                                        <GradientStop Color="Silver" Offset="0.0" />
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="ButtonBase.IsPressed" Value="True">
                            <Setter Property="UIElement.Effect">
                                <Setter.Value>
                                    <DropShadowEffect BlurRadius="10" Color="Black" Direction="0" Opacity="0.6" RenderingBias="Performance" ShadowDepth="0" />
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Button.Template>
        </Button>

6、三态按钮及背景色、文字颜色变化

        <Style x:Key="Style.OkOperationButton" TargetType="ButtonBase">
            <Setter Property="Width" Value="110" />
            <Setter Property="Height" Value="44" />
            <Setter Property="FontSize" Value="24" />
            <Setter Property="Background" Value="#FF0087FF" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ButtonBase}">
                        <Border x:Name="Border" Width="{TemplateBinding Width}"
                                Height="{TemplateBinding Height}"
                                CornerRadius="22" Background="{TemplateBinding Background}">
                            <TextBlock x:Name="TextBlock"
                                       Text="{TemplateBinding Content}"
                                       FontSize="{TemplateBinding FontSize}"
                                       HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                       VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                        </Border>
 
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background"
                                        Value="#FF888888" />
                                <Setter TargetName="TextBlock" Property="Foreground" Value="#FF111111" />
                            </Trigger>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter Property="Background"
                                        Value="#FFfcac1c" />
                                <Setter TargetName="TextBlock" Property="Foreground" Value="#FFFFFFFF" />
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter TargetName="Border" Property="Background" Value="#4D0087FF" />
                                <Setter TargetName="TextBlock" Property="Foreground" Value="#4DFFFFFF" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

提示:TemplateBinding用来实现引用时给控件复制

如:

Text="{TemplateBinding Content}",使用:Content="确定"

FontSize="{TemplateBinding FontSize}" 使用:FontSize="18"

7、自定义控件

(1)解决方案→添加新建项→自定义控件(WPF)

(2)CustomControl.cs

using System;
……
using Button = System.Windows.Controls.Button;
 
namespace StudentImages
{
    
    public class CustomControl : Button
    {
        static CustomControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
        }
 
        public ImageSource Icon
        {
            get
            {
                return (ImageSource)GetValue(IconProperty);
            }
            set { SetValue(IconProperty, value); }
        }
         
        public static readonly DependencyProperty IconProperty
            = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(CustomControl), null);
 
        …………
    }
}

说明:

namespace StudentImages

命名空间,自动生成

public class CustomControl : Button

CustomControl控件名称,自动生成

Button是继承的类,这里手工修改,否则这个自定义控件将会没有按钮的一些属性、事件

Icon是属性的名称

ImageSource是属性的类型

(3)Themes\Generic.xaml

    <Style TargetType="{x:Type local:CustomControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <Border x:Name="PART_Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" />
                            <Grid HorizontalAlignment="Center"  VerticalAlignment="Center">
                                <StackPanel>
                                    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
                                        <Image x:Name="PART_Icon" Source="{TemplateBinding Icon}" Width="50" Height="50"/>
                                        <Image x:Name="PART_MouseOverIcon" Visibility="Collapsed" Source="{TemplateBinding IconMouseOver}" Width="50" Height="50"/>
                                        <Image x:Name="PART_PressIcon" Visibility="Collapsed" Source="{TemplateBinding IconPress}"  Width="50" Height="50"/>           
                                    </Grid>
                                </StackPanel>
                            </Grid>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" TargetName="PART_Border" Value="{Binding MouseOverBackground,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl}}}"/>
                            <Setter Property="BorderBrush" TargetName="PART_Border" Value="{Binding MouseOverBorderBrush,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl}}}"/>
                            <Setter Property="Visibility" TargetName="PART_MouseOverIcon" Value="Visible"/>
                            <Setter Property="Visibility" TargetName="PART_Icon" Value="Collapsed"/>
                            <Setter Property="Visibility" TargetName="PART_PressIcon" Value="Collapsed"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" TargetName="PART_Border" Value="{Binding MouseDownBackground,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl}}}"/>
                            <Setter Property="BorderBrush" TargetName="PART_Border" Value="{Binding MouseDownBorderBrush,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl}}}"/>
                            <Setter Property="Visibility" TargetName="PART_PressIcon" Value="Visible"/>
                            <Setter Property="Visibility" TargetName="PART_Icon" Value="Collapsed"/>
                            <Setter Property="Visibility" TargetName="PART_MouseOverIcon" Value="Collapsed"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

{TemplateBinding xxx}

xxx:如果是原属性,这里直接使用;如果是自定义的,需要在cs文件中注册

源码私信

相关推荐

perl基础——循环控制_principle循环

在编程中,我们往往需要进行不同情况的判断,选择,重复操作。这些时候我们需要对简单语句来添加循环控制变量或者命令。if/unless我们需要在满足特定条件下再执行的语句,可以通过if/unle...

CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅

CHAPTER1TheThreePresentsofD'ArtagnantheElderCHAPTER2TheAntechamber...

CHAPTER 5 The King&#39;S Musketeers and the Cardinal&#39;S Guards 第五章 国王的火枪手和红衣主教的卫士

CHAPTER3TheAudienceCHAPTER5TheKing'SMusketeersandtheCardinal'SGuard...

CHAPTER 3 The Audience 第三章 接见

CHAPTER3TheAudienceCHAPTER3TheAudience第三章接见M.DeTrévillewasatt...

别搞印象流!数据说明谁才是外线防守第一人!

来源:Reddit译者:@assholeeric编辑:伯伦WhoarethebestperimeterdefendersintheNBA?Here'sagraphofStea...

V-Day commemorations prove anti-China claims hollow

People'sLiberationArmyhonorguardstakepartinthemilitaryparademarkingthe80thanniversary...

EasyPoi使用_easypoi api

EasyPoi的主要特点:1.设计精巧,使用简单2.接口丰富,扩展简单3.默认值多,writelessdomore4.springmvc支持,web导出可以简单明了使用1.easypoi...

关于Oracle数据库12c 新特性总结_oracle数据库12514

概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...

【开发者成长】JAVA 线上故障排查完整套路!

线上故障主要会包括CPU、磁盘、内存以及网络问题,而大多数故障可能会包含不止一个层面的问题,所以进行排查时候尽量四个方面依次排查一遍。同时例如jstack、jmap等工具也是不囿于一个方面的问题...

使用 Python 向多个地址发送电子邮件

在本文中,我们将演示如何使用Python编程语言向使用不同电子邮件地址的不同收件人发送电子邮件。具体来说,我们将向许多不同的人发送电子邮件。使用Python向多个地址发送电子邮件Python...

提高工作效率的--Linux常用命令,能够决解95%以上的问题

点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf为什么要学习Linux命令?1、因为Li...

linux常用系统命令_linux操作系统常用命令

系统信息arch显示机器的处理器架构dmidecode-q显示硬件系统部件-(SMBIOS/DMI)hdparm-i/dev/hda罗列一个磁盘的架构特性hdparm-tT/dev/s...

小白入门必知必会-PostgreSQL-15.2源码编译安装

一PostgreSQL编译安装1.1下载源码包在PostgreSQL官方主页https://www.postgresql.org/ftp/source/下载区选择所需格式的源码包下载。cd/we...

Linux操作系统之常用命令_linux系统常用命令详解

Linux操作系统一、常用命令1.系统(1)系统信息arch显示机器的处理器架构uname-m显示机器的处理器架构uname-r显示正在使用的内核版本dmidecode-q显示硬件系...

linux网络命名空间简介_linux 网络相关命令

此篇会以例子的方式介绍下linux网络命名空间。此例中会创建两个networknamespace:nsa、nsb,一个网桥bridge0,nsa、nsb中添加网络设备veth,网络设备间...