[WPF源碼分析]ContentControl依賴項屬性的雙向綁定,two-way binding view's DependencyProperty and ViewModel's variable
阿新 • • 發佈:2018-01-24
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