Determine if a WPF DependencyProperty value is inherited

时间秒杀一切 提交于 2021-02-06 19:55:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!