Home >Backend Development >C++ >Why Is My XAML Binding to a Dependency Property Failing, But Code-Behind Works?
Binding dependency properties fails in XAML but works fine in code-behind.
TestProperty
The declaration of the dependency property lacks the nameof()
operator, resulting in a mismatch between the property name and the XAML binding path. 1. Correctly declare dependency attributes
<code class="language-csharp">public static readonly DependencyProperty TestProperty = DependencyProperty.Register( nameof(Test), typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));</code>
2. Set Bindings.RelativeSource in XAML
<code class="language-xml"><TextBlock Text="{Binding Test, RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBlock></code>
3. Delete the DataContext assignment in the constructor
Remove the DataContext = this;
line of code from the UserControl constructor.
Explicitly set the binding source in code-behind:
<code class="language-csharp">TheControl.SetBinding(MyControl.TestProperty, new Binding { Source = DataContext, ... });</code>
Set binding source implicitly in XAML:
<code class="language-xml"><MyControl Test="{Binding MyText}"></MyControl></code>
In XAML, the implicit binding source defaults to the current DataContext and should be set correctly by the parent window. Setting the DataContext in the constructor of UserControl will overwrite the inherited DataContext, causing binding to fail. By setting Source = DataContext
in the code-behind binding, the binding source is explicitly set to the inherited DataContext, ensuring that the binding is valid.
The above is the detailed content of Why Is My XAML Binding to a Dependency Property Failing, But Code-Behind Works?. For more information, please follow other related articles on the PHP Chinese website!