0
votes

I have a Window with a canvas that has a rectangle at the top of it. It will stretch to fill the width if the canvas. The Canvas is set to be maximized with no toolbar to fill the entire screen like so:

<Window x:Class="Ericsson.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Ericsson"
    mc:Ignorable="d"
    Title="MainWindow"  WindowStyle="None"   
    WindowState="Maximized">
<Window.Resources>
    <SolidColorBrush x:Key = "brushResource" Color = "Black" />
</Window.Resources>

    <Canvas x:Name="MyCanvas" >
        <Rectangle x:Name="TopRect" Fill="Black" Height="120" Canvas.Top="0" Canvas.Left="0" Width="{Binding ElementName=MyCanvas, Path=ActualWidth}"/>
        <Label Content="Welcome to My World" Foreground="#FFFFFF" FontSize="24"
               HorizontalAlignment="Center" 
               VerticalAlignment="Center" 
        />
    </Canvas>

</Window>

My problem is this, I have a label that needs to be centered inside of the dynamic rectangle. The XAML code above puts the label in the upper left hand corner. So "HorizontalAlignment" and "VerticalAlignment" didn't work.

How do I center the label both horizontally and vertically inside of my rectangle?

Thanks

1

1 Answers

1
votes

you can introduce an additional container - Grid - which will align elements properly:

<Canvas x:Name="MyCanvas">
    <Grid Width="{Binding ElementName=MyCanvas, Path=ActualWidth}">
        <Rectangle x:Name="TopRect" Fill="Black" Height="120" />

        <Label Content="Welcome to My World" Foreground="#FFFFFF" FontSize="24"
               HorizontalAlignment="Center" 
               VerticalAlignment="Center" />
    </Grid>
</Canvas>