#152 – Use ReadLocalValue() to Find the Local Value of a Dependency Property

You can use a DependencyObject‘s ReadLocalValue method to get the local value of a dependency property, rather than its effective value.  Recall that the local value is a value set locally, from XAML or code, which takes precedence over all other sources for the base value of a dependency property.  The local value has lower precedence than any coerced values.

Using ReadLocalValue (assuming that this refers to a DependencyObject that registers AgeProperty):

            int ageValue = (int)this.GetValue(AgeProperty);         // Effective value
            int ageLocal = (int)this.ReadLocalValue(AgeProperty);   // Local value

Getting this information for the Age/SuperOld example, we get the following:

            p.Age = 28;
            info = p.AgeInfo();   // Value=28, Local=28

            p.SuperOld = true;
            info = p.AgeInfo();   // Value=999, Local=28

            p.Age = 56;
            info = p.AgeInfo();   // Value=999, Local=56

            p.SuperOld = false;
            info = p.AgeInfo();   // Value=56, Local=56
Advertisement

#134 – Dependency Property Value Sources: #1 – Local Value

The highest priority source for the base value of a dependency property is the property’s local value, set in XAML for the element that owns the property, or set from code.  If a local value is provided, it will override all other possible sources for the base value of the property.

In the following example, the 2nd Label provides a local value for the FontStyle property, overriding the inherited value.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:m="clr-namespace:PersonLib;assembly=PersonLib"
        Title="MainWindow" Height="350" Width="525" FontStyle="Italic">
    <StackPanel Orientation="Vertical">
        <Button Content="Run" Height="23" Width="75" />
        <Button Content="Skip" Height="23" Width="75" />
        <StackPanel Orientation="Horizontal">
            <Label Content="Inside 2nd StackPanel"/>
            <Label x:Name="lblIndep" Content="I do my own FontStyle" FontStyle="Normal"/>
        </StackPanel>
    </StackPanel>
</Window>

You can also set a local value from code:

            lblIndep.FontStyle = FontStyles.Normal;