#153 – You Can Set the Value of any Dependency Property for any Dependency Object
December 12, 2010 3 Comments
A dependency object will typically use its SetValue method internally, to set dependency property values for dependency properties that the object implements. (See How Dependency Properties Are Implemented).
A DependencyObject can, however, store the value of any dependency property–not just the properties that it implements.
The DependencyObject.SetValue method takes a dependency property reference and a property value (whose type should match the type of the dependency property). Using SetValue, you can actually attach any property value you choose to the dependency object.
Here’s an example, where we set various property values on a Person, which is a DependencyObject. These properties are defined in other WPF classes, but it might be useful to attach these property values to a Person object, if it can make use of them.
Person p = new Person("Samuel", "Clemens"); // Set some some arbitrary property values p.SetValue(FrameworkElement.ContextMenuProperty, myMenu); p.SetValue(UIElement.FocusableProperty, true); p.SetValue(Control.FontSizeProperty, 12.0);
Pingback: #166 – You Can Override Metadata for Any Dependency Property « 2,000 Things You Should Know About WPF
Which makes sense? To define normal dependency property or attached dependency property for these kind of things.
I think that if you find a dep property that works for what you’re trying to do in the dependency object that you’re defining, you can use it. But it’s easy enough to define your own also. In implementing a dependency property, I wouldn’t make it an attached property unless you know that you want to use it elsewhere.