Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top