画布不尊重网格边框?

时间:2014-07-30 09:31:11

标签: c# wpf grid wpf-controls

我有一个简单的网格。

<Grid>

    <Grid.RowDefinitions>
        <RowDefinition Height="35" />
        <RowDefinition Height="35" />
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="50" />
    </Grid.ColumnDefinitions>

    <Canvas Grid.Column="0" Grid.Row="0" Width="1600" Height="35" Background="Black" />
    <TextBlock Grid.Column="0" Grid.Row="1" Width="1600" FontSize="20"
               Text="this is a sample text which respects the borders of the grid"  />

</Grid>

导致:

Canvas vs text

现在我真的很想知道为什么将Canvas绘制到下一列的列中,而文本却没有。如果我将ColumnSpan-Property设置为至少2,我会期待这种行为。但事实并非如此,Canvas也不关心显式ColumnSpan。

这有什么理由吗?我可以在不缩小宽度的情况下将画布限制在其列中吗?

2 个答案:

答案 0 :(得分:1)

此问题的解决方法是将canvas放入其他面板,这些面板尊重父宽度,如StackPanel:

<StackPanel  Grid.Column="0"
                 Grid.Row="0"
                 Orientation="Horizontal">
        <Canvas Background="Black"
                Width="1600"
                Height="35" />
    </StackPanel>

或者甚至当您在第一行第二列中放置任何项目时,该项目将位于前景中,并且画布将位于背景中,因此不可见。

答案 1 :(得分:0)

您的第一个ColumnDefinition Width是星号,这意味着在将宽度分配给自动调整大小的列后,它将占用所有可用宽度。此致您的画布不会覆盖其他列,而是宽度(1600px)太高。