WPF:Grid中的Rectangle忽略边距

时间:2014-10-19 10:37:06

标签: wpf xaml

在我嵌入主视图的用户控件中, 我已经定义了以下布局:

<Grid x:Name="RootGrid"  Margin="0,10,0,0" HorizontalAlignment="Stretch">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="30*" />
            <ColumnDefinition Width="20*" />
            <ColumnDefinition Width="20*" />
            <ColumnDefinition Width="30*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Rectangle Margin="5,0,5,0"
                   Grid.RowSpan="5"
                   Grid.ColumnSpan="4"            
                   Panel.ZIndex="-1"
                   Stroke="Blue"
                   Fill ="Black"
                   StrokeThickness="2"
                  />

在Visual Studio的预览中,它看起来像预期的: - 即考虑到保证金5(用于正确调整)。

不幸的是,在运行期间它是另一个故事。我可以根据需要设置正确的调整(边距),缺少矩形的右边框。

有人可以告诉我,我在这里做错了吗?我不想使用矩形的绝对宽度(这是有效的)。

更新

根据Erno的提议,我使用了边框(这确实更简单):

<Border HorizontalAlignment="Stretch" Margin="10,0,10,0" Style="{StaticResource StatusPanelBorder}">
        <Grid x:Name="RootGrid" HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="30*" />
                <ColumnDefinition Width="20*" />
                <ColumnDefinition Width="20*" />
                <ColumnDefinition Width="30*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

但问题仍然存在。 我将此视图嵌入到主视图中,该视图具有以下布局:

<Grid Width="1600" Height="Auto" HorizontalAlignment="Stretch" Background="{StaticResource NoiseBackground}">
        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="30*" />
            <ColumnDefinition Width="90*" />
            <ColumnDefinition Width="40*" />

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="600" />
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>

子视图嵌入到网格的最后一列。 如果我不使用'Stretch'对齐它可以工作,但我想'拉伸'UI元素。

第二次更新: 问题只是shell视图的宽度较小。问题解决了!

1 个答案:

答案 0 :(得分:2)

向网格添加边框的最佳方法是采用边框并在其中嵌套网格:

<Border>
    <Grid>
       ...
    </Grid>
</Border>

这样,网格和边框将调整您可能想要的方式,您可以控制边距,而不必保留文本块&#39;边距与矩形的边框同步。

修改 看看你添加到问题的xaml我想你将窗口的宽度设置为1600.如果是这样,你设置为1600的网格宽度不适合,因为窗口的宽度包括左边和正确的边界。因此,将网格的宽度强制为1600将在右侧将其切断。

我的建议:不要使用硬编码的尺寸,使用星形尺寸的列和行,并使用最大化的窗口;网格将自动拉伸其内容。