Does anyone know how to determine if the value of a WPF property is inherited? In particular, I'm trying to determine if the DataContext
of a FrameworkElement
was inherited from the parent or set directly on the element itself.

- 18,274
- 9
- 70
- 161

- 275
- 1
- 2
- 8
2 Answers
DependencyPropertyHelper.GetValueSource
will give you a ValueSource
, which includes a property for retrieving the BaseValueSource
. The BaseValueSource
enumeration tells you where the DependencyProperty
is getting its value from, such as inherited from parent, set via a style or set locally.

- 175,602
- 35
- 392
- 393
Updated after more digging
There is a ReadLocalValue
method which is stupidly Read instead of Get so hard to spot in intellisense. (I think Apress' WPF book had a note about this actually.) It will return UnsetValue if the value hasn't been set.
if (ReadLocalValue(Control.DataContextProperty) !=
DependencyProperty.UnsetValue)
{
// Data context was set locally.
}
If you for some reason need to get all locally set properties, you can use LocalValueEnumerator.
LocalValueEnumerator enumerator = GetLocalValueEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current.Property == Control.DataContextProperty)
{
// DataContext was set locally
}
}
And these two methods really make me wonder. Read instead of Get in the ReadLocalValue and a collection which you cannot iterate with foreach in GetLocalValueEnumerator. It's like .Net has these nice standard things which the WPF team just decided to ignore.

- 7,884
- 2
- 32
- 47
-
I was using `ReadLocalValue` before to determine whether a value was set in a custom `Panel`. It lead to some really weird behavior where when a value was applied by a style, my panel would still believe the value wasn't set. Only when calling `SetValue`, would the panel start outlining my elements the way they were supposed to, although `GetValue` did return the values correctly. The proper way to go about this is as per [Kent's answer](http://stackoverflow.com/a/809480/590790), which gives you all of the information, rather than just the side effect (local value). – Steven Jeuris Feb 22 '15 at 23:20