为什么在WPF中绑定时不调用该属性?

为什么在WPF中绑定时不调用该属性?,wpf,data-binding,dependency-properties,Wpf,Data Binding,Dependency Properties,我不知道为什么绑定时不调用该属性。代码如下: <myusercontrol Text ="{Binding Description, UpdateSourceTrigger=LostFocus,Mode=TwoWay, ValidatesOnDataErrors=True}" IsReadOnly ="{Binding AllowEditing}" /> 消息框永远不会显示!任何想法 除了GetValue和SetValue调用之外,决不能在依赖项属性getter和setter中

我不知道为什么绑定时不调用该属性。代码如下:

<myusercontrol
Text ="{Binding Description, UpdateSourceTrigger=LostFocus,Mode=TwoWay, ValidatesOnDataErrors=True}" 
 IsReadOnly ="{Binding AllowEditing}"
/>

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

除了GetValue和SetValue调用之外,决不能在依赖项属性getter和setter中放入任何逻辑。这非常重要,因为XAML绑定将直接通过GetValue和SetValue调用,而不是通过代码隐藏属性!这就是为什么你从来没有看到过MessageBox。更好的方法是使用DependencyProperty.Register方法添加回调方法。添加回调时存在重载。然后,只要值发生变化,就会调用该方法,您可以将逻辑放在那里


另一个问题-为什么要使用OnPropertyChanged?依赖项属性内置了更改通知,您不应该为它们调用OnPropertyChanged。

我使用了回调,但甚至没有触发回调。您确定绑定可以正常工作吗?您的输出窗口是否有任何绑定错误?请尝试以下方法调试绑定:diag:PresentationTraceSources.TraceLevel=High,其中diag定义为System.Diagnostics namespace.Hi,刚刚再次检查,它会触发回调,但现在我需要将IsReadOnly设置为e.NewValue。如果这样做,则会启动一个无限循环。您的做法是错误的。我现在看到您正试图将值设置为与输入值相反的布尔值。但这显然是错误的逻辑。为什么要尝试将IsReadOnly属性设置为e.NewValue?IsReadOnly已经是e.NewValue。我认为在应用依赖属性之前,您需要进一步阅读它们是如何工作的。
 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");
            }
        }