首页 > 其他分享 >WPF利用依赖属性和命令编写自定义控件

WPF利用依赖属性和命令编写自定义控件

时间:2023-08-18 10:44:10浏览次数:35  
标签:控件 自定义 Windows System using WPF public SelfControl

以实例讲解(大部分讲解在代码中)


1,新建一个WPF项目,添加一个用户控件之后在用户控件里面添加几个控件用作测试,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <UserControl x:Class="SelfControlDenpendy.SelfControl"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"              mc:Ignorable="d"              d:DesignHeight="300" d:DesignWidth="300">     <Grid>         <StackPanel Width="200" Height="250" Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center">             <TextBox Width="180" Height="50" x:Name="id" Margin="5"></TextBox>             <TextBox Width="180" Height="50" Text="{Binding ElementName=id,Path=Text}" Margin="5"></TextBox>             <Button Height="26" Width="120" x:Name="show" Margin="5" Content="测试绑定控件自身命令"                    <strong> Command="{Binding ChangedIndexCommand}"                     CommandParameter="{Binding ElementName=id,Path=Text}</strong>"></Button>             <Button Height="26" Width="120" x:Name="buttonout" Margin="5"                     <strong>Command="{Binding ButtonCommend, Mode=TwoWay}"</strong> Content="测试绑定外部命令" ></Button>         </StackPanel>     </Grid> </UserControl>

  2,打开用户控件后台代码编写依赖属性以及命令(需要引入GalaSoft.MvvmLight.dll)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 using System; using System.Collections.Generic; using System.Linq; using System.Text; 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 SelfControlDenpendy {     /// <summary>     /// SelfControl.xaml 的交互逻辑     /// </summary>     public partial class SelfControl : UserControl     {         public SelfControl()         {             InitializeComponent();             DataContext = this;//注意此处用于绑定的源必须写,也可把所有依赖代码写在ViewModel里面             ChangedIndexCommand= new RelayCommand<string>(AutoPaging);//注意带参数的命令的写法         }           void AutoPaging(string s)//命令执行带参数的方法         {             MessageBox.Show(s);         }     static SelfControl()//依赖属性的赋值必须写在静态函数里面因为是依赖属性静态只读在家上此处需要在初始化时就注册依赖属性古写在此处         {               //也可不写在此处而写在字段定义出对其直接赋值            UIPropertyMetadata md = new UIPropertyMetadata("", PropertyInputNameChanged);//第一个参数代表默认值(注意类型)            SelfControl.InputNameProperty = DependencyProperty.Register("InputName"typeof(string), typeof(SelfControl), md);//最后一个参数用于当依赖属性值改变是调用md指定的方法            ChangedCommandProperty =//内部访问命令            DependencyProperty.Register("ChangedCommand"typeof(ICommand), typeof(SelfControl), new PropertyMetadata(null));//不许要默认值时写null或不要最后一个参数            ButtonCommendProperty =//外部绑定命令            DependencyProperty.Register("ButtonCommend"typeof(ICommand), typeof(SelfControl), new PropertyMetadata(null));         }              public ICommand ButtonCommend        {          get return (ICommand)GetValue(ButtonCommendProperty); }          set { SetValue(ButtonCommendProperty, value); }        }         public ICommand ChangedCommand        {          get return (ICommand)GetValue(ChangedCommandProperty); }          set { SetValue(ChangedCommandProperty, value); }        }         public static readonly DependencyProperty ChangedCommandProperty;//可以不用敲代码只用输入propdp按Tab即可完成编写         public static readonly DependencyProperty InputNameProperty;         public static readonly DependencyProperty ButtonCommendProperty;         public string InputName         {             get return (string)GetValue(SelfControl.InputNameProperty); }             set { SetValue(SelfControl.InputNameProperty, value); }         }                    private static void PropertyInputNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)//此方法非常重要可用于编写逻辑代码         {                         SelfControl sc = (SelfControl)d;               string str = (string)e.NewValue;//外部赋给依赖属性的值(注意依赖属性的类型)               if (str != "" && str != null)             {                 sc.id.Text = str.ToString();             }         }     }     } }

  3,在主窗口中就可以使用此用户控件(注意引入命名空间)

1 2 3 4 5 6 7 8 9 10 11 12 <Window x:Class="Dependency.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:loac="clr-namespace:Dependency"         Title="MainWindow" Height="350" Width="600">     <Grid>         <TextBox x:Name="tt" Margin="428,70,32,208"></TextBox>         <loac:SelfControl x:Name="sc" Margin="10,10,189,60" RenderTransformOrigin="0.456,0.7"                           ButtonCommend="{Binding AutoCommand}"></loac:SelfControl>         <Button x:Name="bt" Margin="225,283,49,0" Content="测试依赖属性" Click="bt_Click"></Button>     </Grid> </Window>

  4,后台逻辑代码

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 using GalaSoft.MvvmLight.Command; using System.Windows; using System.Windows.Input;   namespace Dependency {     public partial class MainWindow : Window     {             public MainWindow()         {             InitializeComponent();             DataContext = this;             AutoCommand = new RelayCommand(showcommend);//不带参数的命令             AddUserCommand = new RelayCommand(ExecuteAddUser, CanExecuteAddUser);//添加判断的命令             bt.Command = AutoCommand;//赋值命令,用于关联命令             sc.ButtonCommend = AutoCommand;//关联依赖命令         }         void showcommend()         {             MessageBox.Show("测试");         }         public ICommand AutoCommand { getprivate set; }         private ICommand m_ButtonCommand;//此处并未使用此命令,只是显示一般命令的写法         public ICommand ButtonCommand         {             get             {                 return m_ButtonCommand;             }             set             {                 m_ButtonCommand = value;             }         }         public ICommand AddUserCommand { getprivate set; }         void ExecuteAddUser()         {             //逻辑代码         }         bool CanExecuteAddUser()         {             //逻辑代码             return true;         }         private void bt_Click(object sender, RoutedEventArgs e)         {             sc.InputName = tt.Text.ToString();             AutoCommand.Execute(null);//执行定义的命令可代替bt.Command = AutoCommand;         }     } }

  1,若出现在XAML使用用户控件依赖命令时出现“未识别或无法访问”的提示时重新编译或生成一下即可

     2,有可能出现把自定义命令赋值给用户控件的命令但是出现没有调用执行方法,此时建议改用绑定关联,或检查用户控件中使用命令的位置是否合适

     3,依赖属性的默认值类型错误,注意修改依赖属性注册处的最后一个参数

标签:控件,自定义,Windows,System,using,WPF,public,SelfControl
From: https://www.cnblogs.com/webenh/p/17639776.html

相关文章

  • WPF使用WPFMediaKit/AForge调用摄像头示例 .net core 8.0 也支持
    调用摄像头使我们经常会用到的一个功能,可以根据摄像头捕捉到的图像进行分析处理来做很多的东西,比如电子档案、图像识别、AI分析等等。本示例中主要介绍Nuget最常用的两个调用摄像头的轮子WPFMediaKit、AForge环境:VS2019,.NetFramework472WPF  (.netcore8.0 也支持)WPFMe......
  • C# wpf 使用GDI+实现截屏
    wpf截屏系列第一章使用GDI+实现截屏(本章)第二章使用DockPanel制作截屏框第三章实现截屏框实时截屏第四章使用ffmpeg命令行实现录屏文章目录wpf截屏系列前言一、引用System.Drawing方法一、引用系统程序集方法二、NuGet获取跨平台Drawing二、实现截屏1.简单截屏2.绘制鼠标3.转......
  • C# wpf 实现截屏框实时截屏功能
    wpf截屏系列第一章使用GDI+实现截屏第二章使用DockPanel制作截屏框第三章实现截屏框实时截屏(本章)第四章使用ffmpeg命令行实现录屏文章目录wpf截屏系列前言一、实现步骤1、获取截屏区域2、隐藏控件(1)问题(2)解决方法3、截屏二、完整代码三、效果预览总结前言在《C#wpf使用DockP......
  • golang Gin框架 自定义日志形式
    funcmain(){ router:=gin.New() //LoggerWithFormattermiddlewarewillwritethelogstogin.DefaultWriter //Bydefaultgin.DefaultWriter=os.Stdout router.Use(gin.LoggerWithFormatter(func(paramgin.LogFormatterParams)string{ //yourcustomfo......
  • 如何让WPF中的ValidationRule实现参数绑定
    背景应用开发过程中,常常会对用户输入内容进行验证,通常是基于类型、范围、格式或者特定的要求进行验证,以确保输入符合预期。例如邮箱输入框校验输入内容是否符合邮箱格式。在WPF中,数据模型允许将ValidationRules与Binding对象关联,可以通过继承ValidationRule类并重写Validate方法......
  • 【愚公系列】2023年08月 WPF控件专题 Label、TextBox、PasswordBox控件介绍
    (文章目录)前言WPF控件是WindowsPresentationFoundation(WPF)中的基本用户界面元素。它们是可视化对象,可以用来创建各种用户界面。WPF控件可以分为两类:原生控件和自定义控件。原生控件是由Microsoft提供的内置控件,如Button、TextBox、Label、ComboBox等。这些控件都是WPF中常见......
  • WPF --- 非Button自定义控件实现点击功能
    引言今天在做一个设置文件夹路径的功能,就是一个文本框,加个按钮,点击按钮,弹出FolderBrowserDialog再选择文件夹路径,简单做法,可以直接StackPanel横向放置一个TextBox和一个ImageButton,然后点击按钮在后台代码中给ViewModel的FilePath赋值。但是这样属实不够优雅,UI不够......
  • [WPF]WPF中MVVM模式按下ESC键退出窗口
    首先在XAML中定义监听按键<Window.InputBindings><KeyBindingKey="Esc"Command="{BindingCloseWindowCommand}"CommandParameter="{BindingRelativeSource={RelativeSourceFindAncestor,Ancest......
  • Python实现自定义请求头消息headers
    使用python爬虫爬取数据的时候,经常会遇到一些网站的反爬虫措施,一般就是针对于headers中的User-Agent,如果没有对headers进行设置,User-Agent会声明自己是python脚本,而如果网站有反爬虫的想法的话,必然会拒绝这样的连接。而修改headers可以将自己的爬虫脚本伪装成浏览器的正常访问,来......
  • 为远程群晖NAS的自定义域名免费申请SSL证书
    概述ERP系统对于企业来说重要性不言而喻,不管是财务、生产、销售还是采购,都需要用到ERP系统来协助。但ERP中这些重要数据属于企业机密文档,往往需要本地化管理,只能部署在企业内网之下。有时候我们会遇到在外需要远程登录ERP临时处理紧急事务,我们可以通过内网穿透来解决,将ERP服务端端......