两个盒子的边距不正确

时间:2018-06-13 17:30:03

标签: c# wpf margins

所以我有两个盒子,这里的目标是让两个盒子从窗口边缘具有完全相同的边距。不幸的是,在WPF中,你只能从左侧获得边距,而不是两者,所以为了确保这一点,我有以下公式;

  

第二个方框的边距等于窗口宽度减去第一个方框的边距减去方框的大小。

这可以用数学备份, 工作。所以我确实得到了我的计划,因为它是被动的。所以现在我有这个形象:

WPF窗口 enter image description here

中间的文字是为了证明这个计算是正确的。 (只是你知道,每个盒子的宽度是500px)所以,第一个数字是第一个盒子的边距。第二个是第二个边距,最后一个是窗口大小。算一算,你有这个等式:

  

(1936 - 88) - 500 = 1348

然而,这确实有效,但是,如果您查看图像,右边的框比左边的框更接近边缘。如果您调整大小,也会发生这种情况,这不仅仅是在最大化时。怎么了,怎么解决这个问题?

这是我的XAML代码:

<Window x:Class="Horizon_Chat.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:Horizon_Chat"
        xmlns:i="clr-namespace:Horizon_Chat"
        i:WindowEx.ShowIcon = "false"
        mc:Ignorable="d"
        Title="Horizon Chat" Height="900" Width="1280" WindowStartupLocation="CenterScreen" MinWidth="600" MinHeight="600" WindowState="Maximized">
    <Grid>
        <TextBlock x:Name="welcomeTitleText" HorizontalAlignment="Center" Margin="0,-200,0,0" TextWrapping="Wrap" Text="Hello Camden!" VerticalAlignment="Center" FontFamily="Muli" FontSize="60"/>
        <Border x:Name="topBorder" BorderBrush="#FF646464" BorderThickness="0,0,0,4" HorizontalAlignment="Left" Height="41" VerticalAlignment="Top" Width="1273" Margin="0,32,0,0"/>
        <Ellipse Fill="#FF30B44E" HorizontalAlignment="Left" Height="50" Margin="10,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="50" StrokeThickness="3"/>
        <Border x:Name="chatsBox" BorderBrush="Black" BorderThickness="3" HorizontalAlignment="Left" Height="250" Margin="58,594,0,0" VerticalAlignment="Top" Width="500"/>
        <Border x:Name="friendsBox" BorderBrush="Black" BorderThickness="3" HorizontalAlignment="Left" Height="250" Margin="724,594,0,0" VerticalAlignment="Top" Width="500"/>
    </Grid>
</Window>

1 个答案:

答案 0 :(得分:0)

您正在寻找的是网格,将ColumnDefinition Widths设置为矩形宽度+您想要的边距。用于中间Column&#39; s Width的*表示&#34;填写可用空间&#34;。 Margin参数设置为(左,上,右,下)。这允许您指定右手Margin

<Window x:Class="ForStackoverflow.MainWindow"
    ...
    xmlns:local="clr-namespace:ForStackoverflow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition />
            <ColumnDefinition Width="100" />
        </Grid.ColumnDefinitions>

        <Rectangle Margin="15 0 0 0" 
                   StrokeThickness="5" 
                   Stroke="Black"
                   Height="80"
                   Grid.Column="0"/>

        <Rectangle Margin="0 0 15 0" 
                   StrokeThickness="5" 
                   Stroke="Black"
                   Height="80"
                   Grid.Column="2"/>
    </Grid>
</Window>