Can anybody explain me what a dependency property is in WPF and what is its use. I know there are a lot of tutorials on google for it, but they teach how to create a dependency property. I am confused as to where I would use it. I mean will I use it in XAML? If anybody could explain me in simple terms, that would be great.
It would be nice if a simple example is shown along with XAML, with example, of how I might use the property, and what would be the effect after I use it. Thanks a lot for all your answers..
The many links listed should give you a good idea of what dependency properties are, but in general, the easiest way to think about them I believe is the following:
Dependency properties are what you need to use for properties of user interface elements, if you want to be able to bind them using WPF's data binding. In order to be the "Target" of a data binding operation, you'll need to make the property a Dependency Property.
When you're implementing a standard class (which becomes the DataContext of a "control"), you'll want to use INotifyPropertyChanged instead of DPs. This allows that class to be a binding "Source".
In general, you'll only want to make Dependency Properties if you're making something that will be bound in XAML, as the Target
of a UIelement. For example, say we have XAML like this:
<local:MyControl ControlProperty="{Binding SomeProperty}" />
Normally, ControlProperty
will be a Dep. Property, since it's the binding target, and SomeProperty will be a standard CLR property (not a DP), in a class that implements INotifyPropertyChanged.
A Dependency Property does not store its value in a field, but rather in some hashtable. Thus it needs less memory, which is important especially for GUI objects, because most properties will retain their default values und thus those don't take up any more memory. Dependency properties are a bit slower though, because of boxing to and fro object and looking up in the hashtable.
The Dependency Object framework furthermore allows for a lot of features like change notifications etc. I found a good resource that explains the inner workings here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c33a8359-58be-430d-b949-cb6e6f32d8aa
I agree the syntax to declare them is a bit ugly, but you can create helpers to alleviate that a bit.
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