Unable to bind DependencyProperty database

I have a UserControl with DependencyProperty. I set its value in the host window using a data binding expression. However, it does not work properly.

Snapshot from user control code:

public class ViewBase : UserControl { public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register( "ViewModel", typeof(ViewModelBase), typeof(ViewBase)); public ViewModelBase ViewModel { get { return GetValue(ViewModelProperty) as ViewModelBase; } set { SetValue(ViewModelProperty, value); } } } 

And from XAML (note: CasingListView inherits from ViewBase):

 <CasingEditor:CasingListView x:Name="_casingListView" ViewModel="{Binding CasingListViewModel}" /> 

What happens is nothing. In particular, the setter is never called, and the property remains zero. I know that the source property CasingListViewModel has a value because I tried to associate it with another property (DataContext), and it worked fine.

I thought the dependency property could be database bound. I'm wrong?

+4
source share
1 answer

As it sometimes happens, the problem was not quite what we thought.

I mentioned that the setter was never called. It's true. The above code is slightly cropped to make it clearer. Unfortunately, I also deleted the expression in the setter following the call to SetValue. This statement assigned a DataContext value, something like this:

 public ViewModelBase ViewModel { get { return GetValue(ViewModelProperty) as ViewModelBase; } set { SetValue(ViewModelProperty, value); DataContext = value; } } 

As I now learned from this excellent article , the setter actually circumvented when the property was set through data binding. The structure instead works directly against DependencyObject. Thus, the property was actually set, but the setter was never called (as I already mentioned), and the consequence was that the DataContext remained null and nothing worked.

So: First, I apologize for asking an undeniable question. Secondly, as a way to compensate for this, I can convey very important advice:

Never put anything other than GetValue () and SetValue () on the getter / setter property, because they are not always called!

Edit: Later, I also discovered another problem with this approach. By setting the DataContext in this way, I actually lose the original data context, which primarily supports binding. As a result, the immediately reset property is null. So overall not a very good approach.

+6
source

All Articles