views:

65

answers:

2

I need this dependency property to be accessible for read operations only. Outside objects should not be able to assign values to it.

+4  A: 

Yes, you can.

MSDN has an entire section describing how to define and use Read-Only Dependency Properties.

The main issue is to call DependencyProperty.RegisterReadOnly instead of Register. Also, if you create a property on the object to handle this, make sure to only implement a public getter in the property, and not a public setter.

Reed Copsey
+6  A: 

Yes, of course (think IsMouseOver for why read-only dependency properties should exist). MSDN has a great article on the subject.

There are some issues implementing read-only dependency properties and in some situations they will not work. However, it is possible in some cases. For those cases, the following is a brief guide to implementing a readonly dependency property:

  1. Use RegisterReadOnly instead of Register.
  2. Do not expose a public set method in your wrapped property.
  3. The return value from RegisterReadOnly is of type DependencyPropertyKey (instead of the usual DependencyProperty). Store but do not expose this value.

The linked article will give you the necessary details.

Jason