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

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

liuian 2025-05-02 19:36 9 浏览

源码私信联系

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文件中注册

源码私信

相关推荐

iOS9不越狱也能用:苹果Xcode 7编译安装第三方应用教程

在苹果iOS9正式版系统中,即使你不越狱现在也可以安装一些AppStore中根本不存在的应用程序,听上去感觉有些不可思议是吧,一起来看看这到底是怎么做到的。需要准备的东西:你需要准备一台Mac、X...

Python+Appium控制 iOS 真机,滑动、输入、点击全搞定!

移动端自动化测试中,Appium+iOS测试算是门槛稍高但非常关键的一环。很多测试同学面对XCUITest+真机操作时,总觉得“设备连不上”、“控件找不到”、“滑动失败”。先看效果今天我用...

从零到一:用Cursor和Xcode打造你的iOS App!

想要开发自己的iOSApp吗?跟随我们的教程,从前期准备到App上架,一步步教你如何实现!"步骤1:开发App的前期准备"设备和软件:你需要一台Mac电脑、免费的Xcode和Curs...

苹果向开发者推送visionOS 2.5的第四个测试版

近日,苹果面向开发者正式推送了visionOS2.5的第四个Beta开发者预览版,版本号为22O5467a。开发者只需打开设备端的设置应用,在相关选项中找到“开发者测试版”开关,即可开启下...

苹果向开发者推送visionOS 2.5的第一个测试版

苹果公司近日向其注册开发者推送了visionOS2.5更新的第一个Beta测试版,版本号为22O5442g。为了安装这一测试版,开发者们只需通过VisionPro设备上的“设置”应用...

iPhone 16 Pro Max Xcode首选,iPad Pro 2024开发利器

最佳开发者适配机型榜1.iPhone16ProMax(A18Pro模拟器优化)2.iPadPro2024(M4芯片多任务)3.iPhone15Pro(Xcode调试工具)4.iP...

react native中自定义 URL Scheme并跳转到指定页面

在ReactNative中实现类似Android的自定义URLScheme(myapp://open)并跳转到指定页面,可以通过以下步骤完成。ReactNative提供了对深度链接(...

传闻暗示 iPhone 将推出桌面模式(苹果推出页面怎样才能保持推出前的状态)

最近,除了有关iOS视觉效果大幅重新设计和更像Mac的iPadOS体验的传闻外,还有一个有趣的传闻正在流传:iPhone可能会获得某种桌面模式。MajinBu上周写道,一些匿名消息人士称,...

苹果visionOS 1.3首个测试版开启推送 建议谨慎下载

【CNMO科技消息】据外媒报道,开发者现已能够下载体验visionOS1.3首个测试版,只需将其安装在VisionPro上即可。这一版本的发布紧随5月7日释出的第五个测试版之后,而在此之前,4月3...

XcodeBuildMCP 让 AI 代理能够通过标准化接口与 Xcode 项目进行交互

项目介绍XcodeBuildMCP是一个ModelContextProtocol(MCP)服务器,提供与Xcode相关的工具,以便与AI助手和其他MCP客户端集成。它旨在通过标准化接口优化开发...

每日学习“Xcode”是什么呢?(xcode是开发什么的)

Xcode是苹果公司为macOS系统量身打造的集成开发环境(IDE),专为开发苹果生态系统内的各类应用程序,其中也包括游戏。以下从特点、安装使用、在游戏开发中的应用方面详细介绍。特点全平台支持:...

升级wpsjs工具包,创建和发布wps加载项

前一段时间wpsjs工具包不能创建、调试和发布wps加载项,目前已修复,请更新到最新版。wpsjs工具包升级到最新版可以创建和发布wps加载项。执行以下命令:npmupdate-gwpsjs...

如何在 TypeScript 中使用Enum(枚举)

在TypeScript中,枚举或枚举类型是具有一组常量值的常量长度的数据结构。这些常量值中的每一个都称为枚举的成员。在设置只能是一定数量的可能值的属性或值时,枚举很有用。一个常见的例子是一副扑克...

Vue独立组件——11个最佳Vue.js日期选择器组件

介绍本文主要介绍几个Vue的时间日期选择器组件,目的在于让开发者们多一些选择,不管是从功能还是从样式,都可以选择一个适合的组件,这些组件没有绝对的好与不好,就看个人如何选择了,以下分别介绍十一个日期选...

ABP Framework 手动升级指南:从6.0.1升级到7.0.0

ABP7.0.0正式版已经发布,ABP-Framework-All-In-One项目同步升级。LeptonXLiteTheme目前还没有包含在源码解决方案中,还是以Nuget包提供,目...