程序员的知识教程库

网站首页 > 教程分享 正文

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

henian88 2025-03-23 19:45:23 教程分享 13 ℃ 0 评论

源码私信联系

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


1、按钮加入图片

        

图片的处理:

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

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

        

3、使用样式

App.xaml中定义样式

        

4、鼠标覆盖变淡

        

样式:

        

5、三态按钮及阴影效果

        

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

        

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

如:

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

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

7、自定义控件

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

添加CustomControl.cs

(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

    

{TemplateBinding xxx}

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

源码私信

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表