tags:

views:

33

answers:

1

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 AllowEditing}"
/>

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!

+2  A: 

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.

Charlie
I used the callback but even the callback is not being triggered.
azamsharp
Are you sure the binding is working then? Does your output window have any binding errors?
Charlie
Try this for debugging the binding:diag:PresentationTraceSources.TraceLevel=High, where diag is defined as the System.Diagnostics namespace.
Charlie
Hi, Just checked again and it fires the callback but now I need to set the IsReadOnly to e.NewValue if that is done then a infinite loop is started.
azamsharp
There are no binding errors in the output window!
azamsharp
You're going about this the wrong way. I see now that you are trying to set the value to the boolean opposite of what the input value is. But this is definitely the wrong place for this logic. And why would you try to set the IsReadOnly property to e.NewValue? IsReadOnly IS e.NewValue already. I think you need to do some more reading on how dependency properties work before applying them.
Charlie
I got it to work. The user control had a reference to the TextBox and so I accessed it through that route and everything works fine now. Thanks!
azamsharp