问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/808883/determine-if-a-wpf-dependencyproperty-value-is-inherited