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

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


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

<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="测试绑定控件自身命令"
                    Command="{Binding ChangedIndexCommand}"
                    CommandParameter="{Binding ElementName=id,Path=Text}"></Button>
            <Button Height="26" Width="120" x:Name="buttonout" Margin="5"
                    Command="{Binding ButtonCommend, Mode=TwoWay}" Content="测试绑定外部命令" ></Button>
        </StackPanel>
    </Grid>
</UserControl>

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

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,在主窗口中就可以使用此用户控件(注意引入命名空间)

<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,后台逻辑代码

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 { get; private set; }
        private ICommand m_ButtonCommand;//此处并未使用此命令,只是显示一般命令的写法
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }
        public ICommand AddUserCommand { get; private 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,依赖属性的默认值类型错误,注意修改依赖属性注册处的最后一个参数

时间: 2024-07-31 12:30:35

WPF利用依赖属性和命令编写自定义控件的相关文章

利用windows系统ftp命令编写的BAT文件上传[转]

利用windows系统ftp命令编写的BAT文件上传[转] 利用windows系统ftp命令编写的BAT文件上传[转] 在开发中往往需要将本地的程序上传到服务器,而且用惯了linux命令的人来说.在windows下就比较麻烦了.为了方便特编写一个BAT程序来帮助需要这样功能的人.如果用其他IDE工具自带的FTP功能也可以,^_^!      命令: todev.bat /index.asp  默认d:\cnweb为网站的根目录.      我的 http://www.lawcar.cn/ htt

WPF之依赖属性

一站式WPF--依赖属性(DependencyProperty)一 一站式WPF--依赖属性(DependencyProperty)二 WPF之依赖属性

WPF的依赖属性和附加属性(用法解释较全)

转:https://www.cnblogs.com/zhili/p/WPFDependencyProperty.html 一.引言 感觉最近都颓废了,好久没有学习写博文了,出于负罪感,今天强烈逼迫自己开始更新WPF系列.尽管最近看到一篇WPF技术是否老矣的文章,但是还是不能阻止我系统学习WPF.今天继续分享WPF中一个最重要的知识点——依赖属性. 二.依赖属性的全面解析 听到依赖属性,自然联想到C#中属性的概念.C#中属性是抽象模型的核心部分,而依赖属性是专门基于WPF创建的.在WPF库实现中,

Windbg调试WPF的依赖属性

?? 我们用wndbg调试时,很多时候需要查看某个控件的依赖属性值. 比如:我们查看DataGridColumnHeader的Content依赖属性   1.我们用到的windbg的命令有:!do, !da -details, .formats  2.利用!do查看依赖对象的成员变量, 找到具体依赖属性的地址 0:000> !do 00000000039a71d8 Name:        System.Windows.Controls.Primitives.DataGridColumnHead

WPF: 只读依赖属性的介绍与实践

在设计与开发 WPF 自定义控件时,我们常常为会控件添加一些依赖属性以便于绑定或动画等.事实上,除了能够添加正常的依赖属性外,我们还可以为控件添加只读依赖属性(以下统称"只读属性"),以增加控件的灵活性. 这听起来有些矛盾.只读依赖属性,只能读不能写,却又怎么能提高控件的灵活性呢?想想我们常用的 IsMouseOver 等属性就可以理解,它们都是只读属性,但如果没有它们,想要控制样式将会很困难. 所以,总结来说,只读属性的特点是:无法赋值,不能绑定,不能用于动画,不能验证等:而之所以使

说说WPF的依赖属性

首先,我们先来大概了解一下依赖属性 什么是依赖属性:依赖属性自己没有值,通过依赖别人(如Binding)来获得值. 依赖属性为什么会出现:控件常用字段有限,包装太多属性会占用过高内存,造成浪费.所以用依赖属性,用不着就不用,用得着就用. 怎么声明依赖属性:用public static readonly三个修饰符修饰. 怎么声明实例:使用DependencyProperty.Register方法生成.此方法有三个参数跟四个参数. 怎么操作依赖属性的值:利用依赖对象(Dependency Objec

(WPF)依赖属性

属性触发器: <Button MinWidth=" 75" Margin="10"> <Button.Style> <Style TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Proper

WPF基础到企业应用系列7——深入剖析依赖属性(WPF/Silverlight核心)

一. 摘要 首先圣殿骑士非常高兴这个系列能得到大家的关注和支持.这个系列从七月份開始到如今才第七篇,上一篇公布是在8月2日,掐指一算有二十多天没有继续更新了,最主要原因一来是想把它写好,二来是由于近期几个月在筹备"云计算之旅"系列,所以一再推迟了公布进度. 之前一直都没有想过要录制视频.基本的原因还是怕自己知识有限,从而误导他人,所曾经几次浪曦和51CTO邀请录制视频,我都以工作忙.公司内部培训须要时间和自己有待提高等理由委婉的拒绝了,说实在的.自己也知道自己还有非常多地方有待提高.还

WPF系列 —— 控件添加依赖属性

依赖属性的概念,用途 ,如何新建与使用.本文用做一个自定义TimePicker控件来演示WPF的依赖属性的简单应用. 先上TimePicker的一个效果图. 概念 和 用途:依赖属性是对传统.net 属性的一种封装,使一个传统.net属性支持 WPF 中的 数据绑定.动画.样式 等功能. 新建:任意代码代码文件中 ,输入 propdp 再双击tab键.生成如下的代码块. MyProperty: 依赖属性的名称: ownerclass: 当前依赖属性绑定的所有类; new PropertyMeta