I have a window with DataContext set to itself with this simple XAML layout -
<StackPanel>
<TextBlock Text="{Binding NameCLR}"/>
<TextBlock Text="{Binding NameDP}"/>
</StackPanel>
and in code behind i have two properties NameCLR - CLR property
and NameDP - Dependency Property
.
private string NameCLR
{
get { return "CLRProperty"; }
}
private string NameDP
{
get { return (string)GetValue(NameDPProperty); }
set { SetValue(NameDPProperty, value); }
}
private static readonly DependencyProperty NameDPProperty =
DependencyProperty.Register("NameDP", typeof(string), typeof(MainWindow),
new UIPropertyMetadata("DPProperty"));
Since code-behind is a partial class definition and partial is XAML. So, i was assuming that private property should be visible to XAML. But to my amazement CLR and DP behaves differently.
Private Dependency property is accessible but private CLR property isn't.
I got the output as -
DPProperty
instead of
CLRProperty
DPProperty
Can someone let me know about this different behaviour in DP and CLR property?
The bound property is accessed by the Binding, not by the declaring class. A private CLR property like NameCLR
is inaccessible, hence the Binding won't work.
However, when resolving the property path NameDP
the Binding apparently bypasses the CLR wrapper for that property and directly accesses the underlying dependency property, which was registered with the dependency property system by calling DependencyProperty.Register
. It is not relevant whether you have assigned the returned DependencyProperty reference to a private or public static field in your class. The dependency property was registered for your class, hence it can be looked up.
From the link here -
Dependency properties on a given type are accessible as a storage table through the property system, the WPF implementation of its XAML processor uses this table and infers that any given property ABC can be more efficiently set by calling SetValue on the containing DependencyObject derived type, using the dependency property identifier ABCProperty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With