WPF Control

I am trying to develop a user control with some nested properties, which allows me to use data binding to configure it. For example, I have something like this:

// Top level control public class MyControl : Control { public string TopLevelTestProperty { get { return (string)GetValue(TopLevelTestPropertyProperty); } set { SetValue(TopLevelTestPropertyProperty, value); } } public static readonly DependencyProperty TopLevelTestPropertyProperty = DependencyProperty.Register("TopLevelTestProperty", typeof(string), typeof (MyControl), new UIPropertyMetadata("")); // This property contains nested object public MyNestedType NestedObject { get { return (MyNestedType)GetValue(NestedObjectProperty); } set { SetValue(NestedObjectProperty, value); } } public static readonly DependencyProperty NestedObjectProperty = DependencyProperty.Register("NestedObject", typeof(MyNestedType), typeof (MyControl), new UIPropertyMetadata(null)); } // Nested object type public class MyNestedType : DependencyObject { public string NestedTestProperty { get { return (string)GetValue(NestedTestPropertyProperty); } set { SetValue(NestedTestPropertyProperty, value); } } public static readonly DependencyProperty NestedTestPropertyProperty = DependencyProperty.Register("NestedTestProperty", typeof(string), typeof (MyNestedType), new UIPropertyMetadata("")); } // Sample data context public class TestDataContext { public string Value { get { return "TEST VALUE!!!"; } } } ... this.DataContext = new TestDataContext(); ... 

XAML:

  <local:mycontrol x:name="myControl" topleveltestproperty="{Binding Value}" > <local:mycontrol.nestedobject> <local:mynestedtype x:name="myNestedControl" nestedtestproperty="{Binding Value}" /> </local:mycontrol.nestedobject> </local:mycontrol> 

It works well for the TopLevelTestProperty property, but it does not work for NestedTestProperty. Nested bindings don't seem to work. Can someone help me please? Is there any way to make such a binding? I think this is due to the fact that my nested object does not have a reference to a top-level object, so it cannot be resolved using MyControl DataContext.

+4
source share
1 answer

HB right, the nested control does not inherit the DataContext from mycontrol . Tyr outside of him is clearly:

 <local:mycontrol x:name="myControl" topleveltestproperty="{Binding Value}" > <local:mycontrol.nestedobject> <local:mynestedtype x:name="myNestedControl" DataContext="{Binding ElementName=myControl, Path=DataContext}" nestedtestproperty="{Binding Value}" /> </local:mycontrol.nestedobject> </local:mycontrol> 
0
source

Source: https://habr.com/ru/post/1382843/


All Articles