Tuesday, May 3, 2011

determine if a wpf dependencyproperty value is inherited

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.

Thanks, - Mike

From stackoverflow
  • 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.

  • 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.

    HTH, Kent

  • an enumerator is standard, they just didn't provide a collection that uses that enumerator as the result of it's GetEnumerator method (which is what makes For Each work). also, from my experience, it is generally easier to write hierarchial algorithms in terms of enumerators rather than collections, so it does not surprise me they wouldn't provide this.

0 comments:

Post a Comment