个人技术分享

WPF之依赖项属性

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

namespace Learn
{
   public class MyTest
    {

        // 字段
        private string name = "";
        // 属性
        public string Name { get; set; } = "";
        // 等同
        // private string name ="" 
        // public string Name {get{return name;} set{name=value;}}


        // 依赖项属性:在属性之上,增加了其他功能

    }
}


        // 依赖项属性:在属性之上,增加了其他功能

        public string UserName
        {
            get => (string)GetValue(UserNameProperty);
            set { SetValue(UserNameProperty, value); }
        }

        public readonly static DependencyProperty UserNameProperty;

        static MyControl()
        {
            FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata("123456")
            {
                AffectsArrange = true,
                AffectsMeasure = true,
                AffectsParentArrange = true,
                AffectsParentMeasure = true,
            };

            UserNameProperty = DependencyProperty.Register("UserName",typeof(string),typeof(MyControl),metadata);
        }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace LearnCanvas
{
   public class MyControl:FrameworkElement
    {

        // 字段
        //private string name = "";
        // 属性
       // public string UserName { get; set; } = "";
        // 等同
        // private string name ="" 
        // public string Name {get{return name;} set{name=value;}}


        // 依赖项属性:在属性之上,增加了其他功能

        public string UserName
        {
            get => (string)GetValue(UserNameProperty);
            set { SetValue(UserNameProperty, value); }
        }

        public readonly static DependencyProperty UserNameProperty;

        static MyControl()
        {
            FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata("123456")
            {
                AffectsArrange = true,
                AffectsMeasure = true,
                AffectsParentArrange = true,
                AffectsParentMeasure = true,
                CoerceValueCallback = MyCoerceValue,
                PropertyChangedCallback = MyPropertyChanged
            };

            UserNameProperty = DependencyProperty.Register("UserName",typeof(string),typeof(MyControl),metadata,new ValidateValueCallback(MyValidate));
        }

        private static bool MyValidate(object obj)
        {
            return true;
        }

        private static object MyCoerceValue(DependencyObject d,object baseValue)
        {

            return baseValue;
        }

        private static void MyPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
        {

        }
    }
}