UserControl's DependencyProperty is null when UserControl has a DataContext

后端 未结 3 565
南旧
南旧 2020-12-18 17:36

I have added a DependencyProperty to my View, binding to the DependencyProperty works, but only if I do not also set the DataContext.

GenericView.xaml

3条回答
  •  情深已故
    2020-12-18 17:56

    As @toadflakz said, this is a very common issue in WPF and one that took me a while to get my head around when I was learning WPF. Luckily, the solution is simple. Let's say that we have a UserControl that has an object set as its DataContext and another set as the value of a DependencyProperty that is declared within the UserControl... your situation.

    From within the UserControl XAML, you can data bind to a property of the object set as the DataContext as normal:

    
    

    If you want to data bind to an object from the object set as the value of the DependencyProperty, you can simply use a RelativeSource Binding:

    
    

    Note that both of these Bindings can be used together in the same UserControl as long as both of the DataContext and DependencyProperty properties have been set.

提交回复
热议问题