WPF自定义控件CustomControl中依赖属性、命令的使用

2023-11-04

 Generic.xaml中的UI代码:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfCustomControlLibrary1">
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <StackPanel Orientation="Horizontal"> 
                        <TextBlock x:Name="PART_ContentTextBox" Text="{TemplateBinding ContentMsg}"/>
                        <StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <Button  Margin="10"
                                         Grid.Column="0" Grid.Row="0"  Content="1" x:Name="PART_Button"/>
                                <Button   Command="local:CustomControl1.TestCommand" CommandParameter="1" Margin="10" Grid.Column="0" Grid.Row="1"   Content="2" x:Name="PART_Button2"/>
                                <Button   Command="local:CustomControl1.TestCommand" CommandParameter="2" Margin="10"  Grid.Column="0" Grid.Row="2"   Content="3" x:Name="PART_Button3"/> 
                            </StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <Button  Margin="10"  Grid.Column="1" Grid.Row="0"   Content="4" x:Name="PART_Button4"/>
                                <Button Margin="10"   Grid.Column="1" Grid.Row="1"   Content="5" x:Name="PART_Button5"/>
                                <Button Margin="10"   Grid.Column="1" Grid.Row="2"   Content="6" x:Name="PART_Button6"/>

                            </StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <Button   Margin="10" Grid.Column="2" Grid.Row="0"   Content="7" x:Name="PART_Button7"/>
                                <Button   Margin="10" Grid.Column="2" Grid.Row="1"   Content="8" x:Name="PART_Button8"/>
                                <Button  Margin="10"  Grid.Column="2" Grid.Row="2"   Content="9" x:Name="PART_Button9"/>

                            </StackPanel>
                        </StackPanel>
                      </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

后台代码中, 对Command进行声明和初始化以及寻找元素名, 然后在后台寻找此元素进行相应的操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfCustomControlLibrary1
{
  
    [TemplatePart(Name = CustomControl1.ElementContentTextBox, Type = typeof(TextBlock))]
    public class CustomControl1 : Control
    {
        public CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
            ContentMsg = "Hello World"; 
        }
        private const string ElementContentTextBox = "PART_ContentTextBox";
        private const string Elementbutton = "PART_Button"; 
        Button button = null;
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            button =  GetTemplateChild(Elementbutton) as Button;
            button.Click += Button_Click;
            CommandManager.RegisterClassCommandBinding(typeof(CustomControl1), new CommandBinding(TestCommand, TestExecute, TestCanExecute));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ContentMsg = "李四";
        }

      /// <summary>
      /// Registers a dependency property as backing store for the Content property
      /// </summary>
      public static readonly DependencyProperty ContentMsgProperty =
      DependencyProperty.Register("ContentMsg", typeof(object), typeof(CustomControl1),
      new FrameworkPropertyMetadata(null ));

        /// <summary>
        /// Gets or sets the Content.
        /// </summary>
        /// <value>The Content.</value>
        public object ContentMsg
        {
            get { return (object)GetValue(ContentMsgProperty); }
            set { SetValue(ContentMsgProperty, value); }
        }

        /// <summary>
        /// ICommand 属性
        /// </summary>
        public ICommand ContextMenuCommand
        {
            get { return (ICommand)GetValue(ContextMenuCommandProperty); }
            set { SetValue(ContextMenuCommandProperty, value); }
        }
        /// <summary>
        /// ICommand DependencyProperty
        /// </summary>
        public static readonly DependencyProperty ContextMenuCommandProperty =
            DependencyProperty.Register("ContextMenuCommand", typeof(ICommand), typeof(CustomControl1),
               new PropertyMetadata(null));

        public static readonly RoutedUICommand TestCommand =new RoutedUICommand("Test", "TestCommand", typeof(CustomControl1));
        private static void TestCanExecute(object sender, CanExecuteRoutedEventArgs e)
        { 
            e.CanExecute = true;
        }

        private void TestExecute(object sender, ExecutedRoutedEventArgs e)
        {
            CustomControl1 c = sender as CustomControl1;
            if (c == null) return;
            //你的计算逻辑
            ContentMsg = e.Parameter;
        }
    }
}

对于上面TemplatePartAttribute和Command.两种的使用方法分别是

1、    TemplatePartAttribute就是对UI中的元素命名, 然后在后台寻找此元素进行相应的操作(元素命名以”PART_“开始).此方法不建议使用,因为UI与逻辑耦合

2、建议使用Command,因为它能使UI和逻辑分离. 外部改写UI后, 只需对相应的元素重新绑定内置的Command就可以正常地工作

3、在项目中使用时

<Window x:Class="WpfApp1.MainWindow"
        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:WpfApp1"
        mc:Ignorable="d"
        xmlns:custom="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
        Title="MainWindow" Height="450" Width="800">
 
    <StackPanel>
        <custom:CustomControl1 ContentMsg="{Binding DateTimeMsg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  
                               x:Name="mycustom"  HorizontalAlignment="Left" Margin="55,30,0,0" VerticalAlignment="Top"></custom:CustomControl1>
        <Button Content="dsafsdf" Click="Button_Click" Height="40" Width="100" Margin="10"></Button>
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfCustomControlLibrary1;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MainViewModel mainViewModel = new MainViewModel();
        public MainWindow()
        {
            InitializeComponent();
           
            mainViewModel.DateTimeMsg = "张三";
            this.DataContext = mainViewModel;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(mainViewModel.DateTimeMsg.ToString());
        }
    }

     
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfCustomControlLibrary1
{
  
    public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _DateTimeMsg;
        public string DateTimeMsg
        {
            get
            {
                return _DateTimeMsg;
            }
            set
            {
                _DateTimeMsg = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("DateTimeMsg"));
                }
            }
        }
        private string _ContentMsg;
        public string ContentMsg
        {
            get
            {
                return _ContentMsg;
            }
            set
            {
                _ContentMsg = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ContentMsg"));
                }
            }
        }
        
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF自定义控件CustomControl中依赖属性、命令的使用 的相关文章

随机推荐

  • Java实现八大排序

    汲取知识 分享快乐 让生命不留遗憾 作者 不能再留遗憾了 专栏 Java学习 该文章主要内容 直接插入排序 希尔排序 选择排序 堆排序 冒泡排序 快速排序 递归 非递归 归并排序 递归 非递归 文章目录 前言 什么是排序 稳定性 排序实现
  • Thales

    sudo nmap sP 192 168 0 1 24 Starting Nmap 7 92 https nmap org at 2022 04 20 13 46 CST Nmap scan report for 192 168 0 1 H
  • 内核的位图和位操作接口介绍

    1 内核的位图 1 位图 位图就是用一个bit来表示一个资源的情况 比如要表示32个资源的状态 如果是每个资源用一个int型变量去表示则需要32个int型变量 但是采用位图则只需要1个int型变量 32个bit 2 适用位图的情况 资源只有
  • JavaScript和TypeScript入门

    文章目录 前言 一 JavaScript特点 二 JavaScript初步 一 基本语法 二 流程结构 1 顺序结构 2 选择结构 3 循环结构 三 函数 四 对象 1 创建对象 2 MATH对象 3 日期对象 4 字符串对象 五 数组 1
  • rabbitMQ的详细介绍

    1 概述 RabbitMQ是一个消息中间件 它接受并转发消息 你可以把它当做一个快递站点 当你要发送一个包裹时 你把你的包裹放到快递站 快递员最终会把你的快递送到收件人那里 按照这种逻辑RabbitMQ是一个快递站 一个快递员帮你传递快件
  • 哈希值相同的规律

    分享哈希值相同的一个规律 System out println Aa hashCode System out println BB hashCode 2112 2112 我们发现Aa和BB是相同的哈希值 然后我们多做几次试验可以发现一个规律
  • 作为开发人员您会喜欢的 7 个免费公共 API

    1 JSON 占位符 JSON Placeholder是一项服务 可为您提供用于测试和原型制作的假在线REST API 这是每个开发人员的首选 API 2 谷歌翻译 Google有大量的API 但其中大部分是付费的 值得庆幸的是 Trans
  • 河南省网络安全高校战队联盟CTF训练营-web文件上传第一期

    文件上传 个人介绍 姓名 飞羽 CTF菜菜一枚 例题来源 ctfhub https www ctfhub com pwnthebox https insider pwnthebox com ctfshow https ctf show 工具
  • stduino IDE(国产)安装及使用感受!

    文章目录 一 了解stduino IDE 二 安装stduino 三 stduino完成STM32串口通信 四 总结与使用感受 五 参考 一 了解stduino IDE 大概是受到Ardunio IDE的启发 网上有一个国人版的MCU集成开
  • Sublime Text2中的快捷键一览表(Sublime 键盘快捷键大全 )

    Sublime Text 提供了无比强大的快捷键阵容 如果能够在Coding的时候灵活的使用快捷键 将能够使得你的效率倍增 相信在不久的将来 Sublime Text将是你跨平台使用的最佳Coding利器 Sublime Text 2默认使
  • matlab 求单/多元函数极值

    matlab 求单 多元函数极值 单元函数极值 平时如果手算的话 就会先求导数 再求驻点 最终代值算出极值 如果用matlab代码求的话 就可以减少很多不必要的计算 fun inline 0 5 x exp x 2 ezplot fun 0
  • 一个全新的数字化转型和新的营销方式已经来临!

    云翼港最新推出一套直播系统 一部直播手机 一套直播辅助软件 一个人只需一台直播手机 可以在不同的直播平台进行直播 一个人可以同时管理5 10个账号 甚至更多 轻松实现多平台的直播 这款直播辅助软件不仅可以使用数字人 也支持真人直播 还可以在
  • python从入门到入土

    一 基础语法 1 字变量 字变量 在代码中 被写下来的固定的值 字符串 python中用双引号包裹起来的都是字符串 本代码演示了 各类字变量的写法 通过print语句输出各类字变量 写一个整数字变量 666 写一个浮点数字变量 13 14
  • SQLite 数据库存取图片(QT方式)

    目录 实战演示 效果展示 SQLite 数据库可以存取图片 存取的格式为 BLOB 格式 需要把图片转为 QByteArray 格式进行存取 1 实战演示 以下实战代码 复制便可以直接运行 希望可以帮助到你 include
  • oracle报错:ORA-01839: date not valid for month specified(指定月份的日期无效)

    场景 日期值存的是10位字符串 如2020 02 01 sql筛选时需要选1年以内的 select from t user where to date app date yyyy MM dd gt sysdate 360 1 2 3 查看日
  • linux搭建geth私有节点

    linux创建节点 下载文件并上传服务器解压 Downloads Go Ethereum tar zxvf geth linux amd64 1 10 11 7231b3ef tar gz mv geth linux amd64 1 10
  • 2022年智能机器人与系统国际研讨会(ISoIRS 2022)

    2022年智能机器人与系统国际研讨会 ISoIRS 2022 重要信息 会议网址 www isoirs org 会议时间 2022年10月14 16日 召开地点 中国成都 截稿时间 2022年8月30日 录用通知 投稿后2周内 出版社 IO
  • C/C++时间戳转换函数

    目录 生成时间戳 time函数 函数原型 获取当前时间戳 转换时间戳为北京时间
  • 基于springboot+vue前后端分离的小区物业管理系统

    小区物业管理系统 简介 这是一个 SpringBoot Vue 的前后端分离小区物业管理系统 前端使用了若依的后台管理模板 使用 ElementUI 作为 UI 组件 使用 Vue Router 来进行路由跳转 使用 Vuex 来存储状态信
  • WPF自定义控件CustomControl中依赖属性、命令的使用

    Generic xaml中的UI代码