0

I define Dependency Property for the A class. However, I can query the value of that property in an instance of B. Why?

To illustrate, look a this code (WPF):

using System.Windows;

namespace Sample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var propDefinedForA = DependencyProperty.Register("SomeProperty", typeof(int), typeof(A), new PropertyMetadata(defaultValue: 10));

            var b = new B();        
            var value = b.GetValue(propDefinedForA);

        }
    }

    public class A: DependencyObject
    {
    }   

    public class B: DependencyObject
    {
    }  
}

After the execution of this code, the value is 10. Why is this even possible? I haven't defined the DP for the B class, but for A.

What's the reason of this behavior?

SuperJMN
  • 13,110
  • 16
  • 86
  • 185

1 Answers1

0

From Understanding WPF Dependency Property and Attached Property:

Dependency Property

This is WPF property system, even though this is a property, it is not the same as regular property. The properties are not stored in an internal field, but it is stored in an internal storage system that stores per-instance value of the property.

The dependency property is a public static read-only field that must be registered first. After it has been registered, this static property is used to get and set the value in the internal storage system.

Attached Property

This is also dependency property. The internal storage system takes a DependencyProperty as key to get and set value. Attached property allows an object to to store a value using key that belongs to another class.

Imagine WPF property system is a property bag, and the property bag can take any kind of values. In most cases, the key for this property bag is defined in the class itself, but for attached property, the key is defined in other class.

Basically using Attached Properties you can define properties for controls you don't access their internal state or you can't change their source code.

Jalal
  • 6,594
  • 9
  • 63
  • 100