简体   繁体   中英

WPF/UWP: What is the difference between DependencyObject's GetValue() and ReadLocalValue()?

I'm a WPF developer. I'm curious to know, what is the difference between the GetValue and ReadLocalValue methods for DependencyObject ? I know that GetValue can be used to implement a dependency property, like this:

public static DependencyProperty FoobarProperty =
     DependencyProperty.Register(nameof(Foobar),
         typeof(int),
         typeof(DeclaringClass),
         new PropertyMetadata(0, OnFoobarChanged));

public int Foobar
{
     get { return (int)GetValue(FoobarProperty); }
     set { SetValue(FoobarProperty, value); }
}

private static void OnFoobarChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
     var newValue = (int)e.NewValue;
    // do something with the new value...
}

In a simple explanation, what purpose does ReadLocalValue serve? All I can garner from the MSDN sample is that it may return DependencyProperty.UnsetValue , which doesn't really tell much.

That seems to be about it. For the most part, yes, it is used to

Return the local value, or return the sentinel value UnsetValue if no local value is set.

According to MSDN Reference :

You should use GetValue for most typical "get" operations for a dependency property. ReadLocalValue does not return the effective value for a variety of circumstances where the value was not locally set.

Values that are set by styles, themes, templates, the default value from metadata, or property value inheritance are not considered to be local values. However, bindings and other expressions are considered to be local values, after they have been evaluated.

When no local value is set, this method returns UnsetValue.

If the returned value is other than UnsetValue, you can query the metadata of the requested dependency property to determine whether there is a more specific type that the return value can be converted to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM