我有一个全屏对话框,想要将画布居中。例如,对于标签,它似乎适用于具有Vertical / Horizontalalignment的网格,但是当我尝试这个时,左上角会居中而不是画布的中间:
<Window
Title=""
Topmost="True" WindowStyle="None" WindowState="Maximized"
>
<Grid>
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Canvas>
<Border Margin="20"
Background="White"
BorderBrush="Black"
BorderThickness="2"
Padding="20" >
<DockPanel Margin="10">
<StackPanel DockPanel.Dock="Top" Margin="0 0 0 50"
Orientation="Vertical">
<Label FontSize="32" Content="Hello"></Label>
</StackPanel>
<StackPanel HorizontalAlignment="Right"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<Label FontSize="32" Content="Hello"></Label>
</StackPanel>
</DockPanel>
</Border>
</Canvas>
</Grid>
答案 0 :(得分:4)
那是因为你没有在画布上设置宽度和高度,而在画布的情况下,ActualWidth和ActualHeight属性(用于布局)默认为0。
您可以通过在画布上设置背景来测试这一点 - 在您的情况下,由于上述原因,将不会渲染背景颜色。
要解决此问题,请执行以下操作之一:
答案 1 :(得分:1)
您可以将Border作为Grid的子项而不是Canvas。 (网格可以有多个孩子) 试试这个:
<Window
Title=""
Topmost="True" WindowStyle="None" WindowState="Maximized"
>
<Grid>
<Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Rectangle Canvas.Left="40" Canvas.Top="31" Width="630" Height="41" Fill="Blue" />
<Ellipse Canvas.Left="130" Canvas.Top="79" Width="580" Height="580" Fill="Blue" />
<Path Canvas.Left="61" Canvas.Top="28" Width="133" Height="98" Fill="Blue" Stretch="Fill" Data="M61,325 L293,28" />
</Canvas>
<Border Margin="20"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="WhiteSmoke"
BorderBrush="Black"
BorderThickness="2"
Padding="20">
<DockPanel Margin="10">
<StackPanel DockPanel.Dock="Top" Margin="0 0 0 50" Orientation="Vertical">
<Label FontSize="32" Content="Hello" />
</StackPanel>
<StackPanel HorizontalAlignment="Right"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<Label FontSize="32" Content="Hello" />
</StackPanel>
</DockPanel>
</Border>
</Grid>
</Window>