Binding to ActualHeight does not work

て烟熏妆下的殇ゞ 提交于 2019-12-22 16:40:40

问题


I tried to create a custom control, having a semitransparent rounded background:

<Canvas>
    <TextBlock x:Name="StopText" Text="Some test text"/>
    <Rectangle Fill="SkyBlue"
               Width="{Binding Source=StopText, Path=ActualHeight}" 
               Height="20"  
               RadiusX="5" RadiusY="5" Opacity="0.2"/>
</Canvas>

The problem is that I can't, probably, bind to the ActualHeight/ActualWidth properties, cause they are not dependency ones.

What to do to mantain the rectangle and textbox of same size?


回答1:


The correct binding is to use ElementName, not Source, when binding to another element:

<Canvas>
    <TextBlock x:Name="StopText" Text="Some test text"/>
    <Rectangle Fill="SkyBlue"
               Width="{Binding ElementName=StopText, Path=ActualHeight}" 
               Height="20"  
               RadiusX="5" RadiusY="5" Opacity="0.2"/>
</Canvas>

Also, you do realize that you are binding the width of the Rectangle to the Height of the TextBlock, right?

If this is really the way you want to set up your control, you will want to bind the Rectangle's Width to the TextBlock's ActualWidth, and Height to ActualHeight.

UPDATE Per the comments below, here is an implementation using a Grid with no binding:

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <TextBlock x:Name="StopText" Text="Some test text"/>
    <Rectangle Fill="SkyBlue"
               HorizontalAlignment="Stretch"
               VerticalAlignment="Stretch"  
               RadiusX="5" RadiusY="5" Opacity="0.2"/>
</Grid>

Grid and Canvas use different layout systems, and since you aren't using the functionality the Canvas provides, Grid is the better choice.

The big difference in the child elements is that the Rectangle now just uses Horizontal and VerticalAlignment to Stretch across the entire Grid, instead of worrying about the sizes of anything.



来源:https://stackoverflow.com/questions/3787312/binding-to-actualheight-does-not-work

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