Search code examples
wpfxamlrectangles

Adding content/text in rectangle WPF


This is my code for rectangle :

 <Rectangle x:Name="rect1" Grid.Column="1"  Fill="#FF5C626C" HorizontalAlignment="Left" Height="50" Margin="36,171,0,0" StrokeThickness="2" VerticalAlignment="Top" Width="358" RadiusX="30" RadiusY="50">
        <Rectangle.Triggers>
        </Rectangle.Triggers>
        <Rectangle.Style>

            <Style TargetType="Rectangle">
                <Style.Triggers>

                    <EventTrigger RoutedEvent="Rectangle.MouseEnter">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF767C84" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="Rectangle.MouseLeave">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF5C626C" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
    </Rectangle>

My question is how do i add a text/content in the rectangle ?

One might suggest using a code block, but if u go through my code, youu'll notice that the rectangle changes it's color on mouseover.So if i put a textblock over the rectangle,the mouseover doesn't work properly(as the textblock covers the entire rectangle).

Another suggestion would be to use a border.But i am not sure about this as i need to find the code to apply mouse over effect on a border.

The next suggestion might be to use a button instead.I would've but my rectangle has corner radius and is a bit round-shaped which, if i use a button, would be hard to achieve.

So how do i add content/text inside the rectangle?


Solution

  • If you feel you definitely have to use a rectangle, put it in a grid and add a TextBlock element above it.

    By setting the TextBlock's IsHitTestVisible property to False all hit-testing (mouse events) will be ignored on it and fall through to your rectangle.

    <Grid>
        <Rectangle (...your attributes here...)>
            (...your rectangle code here...)
        </Rectangle>
        <TextBlock Text="Hello World!" IsHitTestVisible="False" />
    </Grid>