简体   繁体   中英

How does property value inheritance work in WPF?

According to MSDN, The property value inheritance enables child elements in a tree of elements to obtain the value of a particular property from parent elements, inheriting that value as it was set anywhere in the nearest parent element.

Please find below the sample example

<Grid Width="300" >
                <Border BorderThickness="1">
                <StackPanel Width="200"  Height="200" Background="AliceBlue">
                    <TextBlock />
                </StackPanel>
                </Border>
            </Grid>

I have 2 questions about the example mentioned above,

  1. The background of TextBlock is not set at textblock level but it obtains value from parent Stackpanel. Similarly, It takes width of 200 from stackpanel but height is not set to 200, why?

  2. As Text property of TextBlock is not set, will it be looking for it in its parents like Stackpanel,Border, Grid? I cannot find a mechanism to set the value of Text property at Panel level.

The dependency property value precedence is well documented .

1) Controls's size isn't inherited, it's measured according to parent's size (available size) and desired size to display content.

2) For that you've to use the FrameworkPropertyMetadata.Inherits option in the attached property declaration. Furthermore, only attached DP can have inherited value:

Although property value inheritance might appear to work for nonattached dependency properties, the inheritance behavior for a nonattached property through certain object-object divisions in the runtime tree is undefined. Always use RegisterAttached to register properties where you specify Inherits in the metadata.

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