XAML binding fails on dependency properties
Data binding for dependency properties has no effect in XAML, but works fine in code-behind. The following code snippet demonstrates the problem:
<code class="language-xml"><UserControl ...="" x:Class="WpfTest.MyControl"> <TextBlock Text="{Binding Test}"/> </UserControl></code>
Dependency properties are defined as follows:
<code class="language-csharp">public static readonly DependencyProperty TestProperty = DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT")); public string Test { get { return (string)GetValue(TestProperty); } set { SetValue(TestProperty, value); } }</code>
In the main window, binding to normal properties works perfectly:
<code class="language-xml"><TextBlock Text="{Binding MyText}"/></code>
However, the same binding in the user control does not update the text:
<code class="language-xml"><MyControl Test="{Binding MyText}" x:Name="TheControl"/></code>
It's worth noting that the binding works fine when implemented in code-behind:
<code class="language-csharp">TheControl.SetBinding(MyControl.TestProperty, new Binding { Source = DataContext, Path = new PropertyPath("MyText"), Mode = BindingMode.TwoWay });</code>
Solution:
Correct dependency property declaration:
<code class="language-csharp">public static readonly DependencyProperty TestProperty = DependencyProperty.Register( nameof(Test), typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));</code>
Binding in UserControl XAML:
<code class="language-xml"><UserControl ...="" x:Class="WpfTest.MyControl"> <TextBlock Text="{Binding Test, RelativeSource={RelativeSource AncestorType=UserControl}}"/> </UserControl></code>
Avoid setting DataContext in UserControl constructor:
Never set the DataContext in the UserControl's constructor. This prevents the UserControl from inheriting its parent's DataContext.
The above is the detailed content of Why Doesn't My XAML Binding Work on a Dependency Property, But Works in Code-Behind?. For more information, please follow other related articles on the PHP Chinese website!