为什么在WPF中没有调用绑定属性?

aza*_*arp 2 data-binding wpf dependency-properties

我不确定为什么没有在Binding上调用该属性.这是代码:

<myusercontrol
Text ="{Binding Description, UpdateSourceTrigger=LostFocus,Mode=TwoWay, ValidatesOnDataErrors=True}" 
 IsReadOnly ="{Binding AllowEditing}"
/>
Run Code Online (Sandbox Code Playgroud)

这是myusercontrol IsReadOnly属性:

 public static DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof (bool),
                                                                                          typeof (
                                                                                              myusercontrol));


        public bool IsReadOnly
        {
            get
            {
                return ((bool) GetValue(IsReadOnlyProperty));
            }

            set
            {
                MessageBox.Show(value.ToString()); 
                SetValue(IsReadOnlyProperty, !value); 
                OnPropertyChanged("IsReadOnly");
            }
        }
Run Code Online (Sandbox Code Playgroud)

永远不会显示消息框!有任何想法吗!

Cha*_*lie 5

除了GetValueSetValue调用之外,你不应该在依赖属性getter和setter中放置任何逻辑.这非常重要,因为XAML绑定将直接通过GetValueSetValue调用,而不是通过代码隐藏属性!这就是你永远不会看到的原因MessageBox.更好的方法是使用该DependencyProperty.Register方法添加回调方法(存在重载以添加回调).然后,只要值发生变化,就会调用该方法,并且可以将逻辑放在那里.

另一个问题 - 你为什么用OnPropertyChanged?依赖属性内置了更改通知,您永远不必调用OnPropertyChanged它们.