DependencyProperty使用中的3个场景,讨论PropertyChangedCallback

本文探讨了Silverlight中控件的数据绑定机制,通过三种不同的绑定方式对比,展示了依赖属性及属性更改回调的使用方法。当直接设置依赖属性或通过DataContext进行绑定时,属性更改回调的触发情况有所不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:项目结构图

image

2:控件SilverlightControl1

前台:

image

后台:

    public partial class SilverlightControl1 : UserControl
    {
        public SilverlightControl1()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty StudentProperty = DependencyProperty.Register("Student", typeof(Student), typeof(SilverlightControl1), new PropertyMetadata(new PropertyChangedCallback(xxx)));

        public Student Student
        {
            get
            {
                return (Student)GetValue(StudentProperty);
            }
            set
            {
                SetValue(StudentProperty, value);
                
            }
        }

        static void xxx(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MessageBox.Show("sss");
        }
    }

3:调用方

前台:

image

后台:

    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        Student student1 = new Student() { StudentName = "hzh" + DateTime.Now.ToFileTime(), Age = 99 };
        Student student2 = new Student() { StudentName = "lmj" + DateTime.Now.ToFileTime(), Age = 99 };
        Student student3 = new Student() { StudentName = "lh" + DateTime.Now.ToFileTime(), Age = 99 };

        //初始化
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //采用非绑定机制
            uc1.Student = student1;
            //采用非绑定机制,对DataContext赋值
            uc2.DataContext = student2;
            //采用绑定机制
            uc3.DataContext = student3;
        }

        //改Model值
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            student1.StudentName = "lmj" + DateTime.Now.ToString();
            student1.Age = 90;
            student2.StudentName = "hzh" + DateTime.Now.ToString();
            student2.Age = 90;
            student3.StudentName = "hzh" + DateTime.Now.ToString();
            student3.Age = 90;
        }

        //更换Model
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            student1 = new Student() { StudentName = "hzh" + DateTime.Now.ToFileTime(), Age = 99 };
            student2 = new Student() { StudentName = "lmj" + DateTime.Now.ToFileTime(), Age = 99 };
            student3 = new Student() { StudentName = "lh" + DateTime.Now.ToFileTime(), Age = 99 };
        }
    }

4:结论

无论是第一种方式,还是第三种方式,都能触发PropertyChangedCallback,而如果调用采用第二种方式,则不会触发PropertyChangedCallback。

源码:SilverlightApplication320110609.rar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值