美文网首页WPF
依赖属性 & 附加属性

依赖属性 & 附加属性

作者: 落地成佛 | 来源:发表于2019-07-23 16:45 被阅读0次

    一、概述

    依赖属性指属性没有值,通过Binding从数据源中获取值

    二、使用

    2.1 依赖属性 Register

        public class Student0:DependencyObject
        {
            public string Name
            {
                get {
                    return (string)GetValue(NameProperty);
                }
                set
                {
                    SetValue(NameProperty, value);
                }
            }
    
            public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student0));
            public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase bind)
            {
                return BindingOperations.SetBinding(this,dp,bind);
            }
        }
    
      stu = new Student0();
                Binding bind = new Binding("Text") { Source=textBox1};
    
                stu.SetBinding(Student0.NameProperty, bind);
               
                textBox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source=stu});
    

    2.2 附加属性 RegisterAttached

        public class Human:DependencyObject
        {
           
        }
    
        public class School : DependencyObject
        {
    
            public static int GetGrade(DependencyObject obj)
            { 
                return (int)obj.GetValue(GradeProperty);
            }
    
            public static void SetGrade(DependencyObject obj, int value)
            {
                obj.SetValue(GradeProperty, value);
            }
    
            // Using a DependencyProperty as the backing store for Grade.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty GradeProperty =
                DependencyProperty.RegisterAttached("Grade", typeof(int), typeof(School), new UIPropertyMetadata(0));
            
        }
    
                Human human = new Human();
                School.SetGrade(human, 15);
                int grade = School.GetGrade(human);
                MessageBox.Show(grade.ToString());
    

    相关文章

      网友评论

        本文标题:依赖属性 & 附加属性

        本文链接:https://www.haomeiwen.com/subject/mzbolctx.html