开发者

Why the property is not called on Binding in WPF?

开发者 https://www.devze.com 2022-12-25 13:17 出处:网络
I am not sure why the property is not being called on Binding. Here is the code: <myusercontrol Text =\"{Binding Description, UpdateSourceTrigger=LostFocus,Mode=TwoWay, ValidatesOnDataErrors=True

I am not sure why the property is not being called on Binding. Here is the code:

<myusercontrol
Text ="{Binding Description, UpdateSourceTrigger=LostFocus,Mode=TwoWay, ValidatesOnDataErrors=True}" 
 IsReadOnly ="{Binding Allo开发者_JS百科wEditing}"
/>

And here is the myusercontrol IsReadOnly property:

 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");
            }
        }

The message box is never displayed! Any ideas!


You should never put any logic in your dependency property getters and setters except for the GetValue and SetValue calls. This is very important, because the XAML binding will go directly through the GetValue and SetValue calls, not through your code-behind property! That is why you are never seeing the MessageBox. A better approach is to add a call-back method using the DependencyProperty.Register method (there is an overload to add a call-back). Then, that method will be called whenever the value changes, and you can place your logic there.

Another question- why are you using OnPropertyChanged? Dependency properties have change notification built-in, you should never have to call OnPropertyChanged for them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号