首页 > Windows开发 > 详细

[WPF源码分析]ContentControl依赖项属性的双向绑定,two-way binding view's DependencyProperty and ViewModel's variable

时间:2018-01-24 19:09:41      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:body   edev   原因   color   turn   invalid   one   depend   rop   

问题:自定义控件的依赖项属性和VIewModel中的变量不能双向绑定

解决思路:对比.net源码 PresentationFramework  /   System.Windows.Controls

原因:定义依赖项属性时没有设置OnChanged方法

解决方法:初始化时绑定Changed方法

.net 源码如下:

/// <summary>
        ///     The DependencyProperty for the Content property.
        ///     Flags:              None
        ///     Default Value:      null
        /// </summary>
        [CommonDependencyProperty]
        public static readonly DependencyProperty ContentProperty =
                DependencyProperty.Register(
                        "Content",
                        typeof(object),
                        typeof(ContentControl),
                        new FrameworkPropertyMetadata(
                                (object)null,
                                new PropertyChangedCallback(OnContentChanged)));
 
        /// <summary>
        ///     Content is the data used to generate the child elements of this control.
        /// </summary>
        [Bindable(true), CustomCategory("Content")]
        public object Content
        {
            get { return GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }
 
        /// <summary>
        ///     Called when ContentProperty is invalidated on "d."
        /// </summary>
        private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            // 根据需要实现自己的方法 
            ContentControl ctrl = (ContentControl) d;
            ctrl.SetValue(HasContentPropertyKey, (e.NewValue != null) ? BooleanBoxes.TrueBox : BooleanBoxes.FalseBox);
 
            ctrl.OnContentChanged(e.OldValue, e.NewValue);
        }
 

 

[WPF源码分析]ContentControl依赖项属性的双向绑定,two-way binding view's DependencyProperty and ViewModel's variable

标签:body   edev   原因   color   turn   invalid   one   depend   rop   

原文:https://www.cnblogs.com/bincoding/p/8342791.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号