This has been bugging me for a while, so I asked a coworker if he could make any sense of it, and now I’m here 😉
How come you can access private members of the holding class in the PropertyChangedCallback of a dependency property?
Let me explain further what i mean through this example:
/// <summary>
/// Interaction logic for ZeControl.xaml
/// </summary>
public partial class ZeControl : UserControl
{
public ZeControl()
{
InitializeComponent();
}
private bool m_Trololo; //Please note that this field is PRIVATE!
#region Text
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ZeControl), new UIPropertyMetadata(
new PropertyChangedCallback((dpo, dpce) =>
{
((ZeControl)dpo).m_Trololo = true; //How the hell?
//this.m_Trololo <-- would not compile, the callback is static.
})));
#endregion
}
Isn’t this breaking encapsulation? how does it even compiles?
I’m asking this mainly because I make use of it in my WPF applications: it allows me to keep a variable private while still accessing it in callbacks.
But since it really doesn’t feel right at all, I wouldn’t want this to be “fixed” in WPF vNext, making my apps incompatible.
Best regards,
bab.
The callback is defined in the same class that owns the private member, nothing wrong with that kind of access. It might seem odd that a private instance member is seemingly accessed “from the outside” but you are still in the same class.