龙空技术网

C# WPF自定义控件

讲讲01 104

前言:

此时看官们对“wpf 颜色选择控件”大致比较看重,各位老铁们都想要知道一些“wpf 颜色选择控件”的相关文章。那么小编同时在网摘上收集了一些对于“wpf 颜色选择控件””的相关文章,希望看官们能喜欢,朋友们快快来学习一下吧!

一.简介

WPF (Windows Presentation Foundation) 允许创建自定义控件,以便在应用程序中重用特定的功能和外观。

创建从Control 类派生的控件时,可使用模板定义它的外观。通过这种方式,可以将运算逻辑从视觉表示形式中分离出来。通过使用命令和绑定(而不是事件)并尽可能避免引用 ControlTemplate 中的元素,也可确保分离 UI 和逻辑。

二.WPF自定义控件的创建

下面创建一个LedControl自定义控件为例。

1. 创建一个新的WPF自定义控件项目

打开Visual Studio并创建一个新的WPF自定义控件项目。在Visual Studio中,选择“文件” > “新建” > “项目”。在“新建项目”对话框中,选择“WPF 自定义控件库”模板。输入项目名称和位置,然后单击“创建”。

2. 设计控件的外观

WPF 中的许多控件使用ControlTemplate定义控件的结构和外观,因为它可以将控件的外观和功能区分开来。重新定义ControlTemplate可以极大地更改控件的外观。

在创建的项目中,打开Generic.xaml 文件。这个文件定义了控件的默认样式和模板。

使用XAML语言在 Generic.xaml 中定义控件的外观。可以使用标准的WPF控件(如Grid、Border、Ellipse等)来构建控件的外观。样式和模板定义了控件的外观和行为,包括边框、背景、文本样式等。

下面为本次编写自定义控件的xaml程序,使用一个椭圆元素,用于表示LED控件。Fill属性使用了TemplateBinding来绑定到控件的Color属性,从而实现了颜色的绑定。

<ResourceDictionary    xmlns=";    xmlns:x=";    xmlns:local="clr-namespace:CustomControl">    <Style TargetType="{x:Type local:LedControl}">        <Setter Property="Template">            <Setter.Value>                <ControlTemplate TargetType="{x:Type local:LedControl}" >                    <Grid>                        <Ellipse x:Name="ellipseLED" Fill="{TemplateBinding Color}"/>                    </Grid>                </ControlTemplate>            </Setter.Value>        </Setter></Style></ResourceDictionary>

3. 定义控件的属性和依赖属性

在控件的代码文件中定义控件的属性。这些属性将用于设置控件的外观和行为。对于支持数据绑定的属性,可以将它们定义为依赖属性。依赖属性允许属性更改时触发通知,并支持数据绑定。

使用依赖属性,可以执行以下操作:

在样式中设置该属性。将该属性绑定到数据源。使用动态资源作为该属性的值。对该属性进行动画处理。

通过调用DependencyProperty.Register 向属性系统注册该属性名,以指定以下内容:

属性的名称。属性类型。拥有属性的类型。属性的元数据。元数据包含属性的默认值、CoerceValueCallback和 PropertyChangedCallback。

LedControl.cs 文件中定义控件的属性。这里定义IsBlinking 的依赖属性,用于控制LED是否闪烁;定义Color的依赖属性,用于设置LED 控件的颜色;定义BlinkFrequency的依赖属性,用于设置LED 闪烁的频率;定义ClickCommand的依赖属性,用于触发鼠标按下事件。

using System;using System.Windows;using System.Windows.Controls;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;namespace CustomControl{    public class LedControl : Control    {        // 静态构造函数,用于注册默认的控件样式        static LedControl()        {            DefaultStyleKeyProperty.OverrideMetadata(typeof(LedControl), new FrameworkPropertyMetadata(typeof(LedControl)));        }        public LedControl()        {            MouseDown += ExecuteClickCommand;        }                 // 获取或设置 LED 控件的颜色         public Brush Color         {             get { return (Brush)GetValue(ColorProperty); }             set { SetValue(ColorProperty, value); }         }         // 获取或设置 LED 控件是否正在闪烁        public bool IsBlinking        {            get { return (bool)GetValue(IsBlinkingProperty); }            set { SetValue(IsBlinkingProperty, value); }        }        // 获取或设置 LED 控件的闪烁频率        public double BlinkFrequency        {            get { return (double)GetValue(BlinkFrequencyProperty); }            set { SetValue(BlinkFrequencyProperty, value); }        }        // 定义 LED 控件的颜色依赖属性        public static readonly DependencyProperty ColorProperty =            DependencyProperty.Register("Color", typeof(Brush), typeof(LedControl), new PropertyMetadata(Brushes.Red));        // 定义 LED 控件是否正在闪烁的依赖属性        public static readonly DependencyProperty IsBlinkingProperty =            DependencyProperty.Register("IsBlinking", typeof(bool), typeof(LedControl), new PropertyMetadata(false, OnIsBlinkingChanged));        // 定义 LED 控件的闪烁频率依赖属性        public static readonly DependencyProperty BlinkFrequencyProperty =            DependencyProperty.Register("BlinkFrequency", typeof(double), typeof(LedControl), new PropertyMetadata(1.0, OnBlinkFrequencyChanged));        // 定义 LED 控件鼠标按下事件依赖属性        public static readonly DependencyProperty ClickCommandProperty =            DependencyProperty.Register("ClickCommand", typeof(ICommand), typeof(LedControl));        public ICommand ClickCommand        {            get { return (ICommand)GetValue(ClickCommandProperty); }            set { SetValue(ClickCommandProperty, value); }        }        private void ExecuteClickCommand(object sender, MouseEventArgs  e)        {            if (ClickCommand != null && ClickCommand.CanExecute(null))            {                ClickCommand.Execute(null);            }        }        // 当 IsBlinking 属性发生变化时调用的静态方法        private static void OnIsBlinkingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)        {            var led = (LedControl)d;            led.UpdateBlinking();        }        // 当 BlinkFrequency 属性发生变化时调用的静态方法        private static void OnBlinkFrequencyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)        {            var led = (LedControl)d;            led.UpdateBlinking();        }        // 更新 LED 控件的闪烁状态        private void UpdateBlinking()        {            if (IsBlinking)            {                StartBlinking();            }            else            {                StopBlinking();            }        }        // 启动 LED 控件的闪烁动画        private void StartBlinking()        {            var animation = new DoubleAnimation            {                From = 1.0,                To = 0.0,                Duration = new Duration(TimeSpan.FromSeconds(BlinkFrequency)),                AutoReverse = true,                RepeatBehavior = RepeatBehavior.Forever            };            var storyboard = new Storyboard();            storyboard.Children.Add(animation);            Storyboard.SetTarget(animation, this);            Storyboard.SetTargetProperty(animation, new PropertyPath(OpacityProperty));            storyboard.Begin();        }        // 停止 LED 控件的闪烁动画        private void StopBlinking()        {            // 清除任何现有的动画            BeginAnimation(OpacityProperty, null);            Opacity = 1.0; // 重置不透明度        }    }}

三、自定义控件的使用及效果

1. 自定义控件的使用

在应用程序中使用自定义控件,并设置属性,绑定事件。实现点击控件闪烁,再次点击停止闪烁的效果。

<Window        xmlns=";        xmlns:x=";        xmlns:d=";        xmlns:mc=";        xmlns:local="clr-namespace:CustomControl"        xmlns:vm="clr-namespace:CustomControl.ViewModel"        x:Class="CustomControl.MainWindow"        mc:Ignorable="d"        DataContext="{x:Static vm:ViewModelLocator.Main}"        Title="MainWindow" Height="182" Width="188">    <Grid >        <local:LedControl HorizontalAlignment="Center" VerticalAlignment="Center" Height="53" Width="50"                         IsBlinking ="{Binding Blinking, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"                        ClickCommand="{Binding StartCommand}"  Color="Gold" BlinkFrequency="0.5"/>    </Grid>

using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;using CustomControl.View;using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Data;namespace CustomControl.ViewModel{    internal partial class MainViewModel: ObservableObject    {        [ObservableProperty]        private bool blinking;        [RelayCommand]        private void Start()        {            Blinking = !Blinking;        }    }}

2.自定义控件的使用效果

视频加载中...

标签: #wpf 颜色选择控件