#153 – You Can Set the Value of any Dependency Property for any Dependency Object

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);

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #153 – You Can Set the Value of any Dependency Property for any Dependency Object

  1. Pingback: #166 – You Can Override Metadata for Any Dependency Property « 2,000 Things You Should Know About WPF

  2. taha says:

    Which makes sense? To define normal dependency property or attached dependency property for these kind of things.

    • Sean says:

      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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: