2016-09-18 69 views
0

这是我的XAML:为什么2个按钮仍然重叠

<Grid> 
     <Button x:Name="top1" Content="top" Width="200" Height="50" VerticalAlignment="Top" HorizontalAlignment="Center"/> 
     <Button x:Name="top2" Content="top" Width="100" Height="25" VerticalAlignment="Top" HorizontalAlignment="Center"/> 
     <Button x:Name="left" Content="left" Width="200" Height="50" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,0,0,0" Click="Button_Click"/> 
    </Grid> 

当我点击左键,我想TOP2按钮,向左走,以避免与TOP1按钮重叠。这里是我的背景代码:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var offset = this.top1.ActualWidth + this.top2.ActualWidth/2; 
    this.top2.Margin = new Thickness(0, 0, offset, 0); 
} 

但是在结果中,top1和top2仍然重叠。 enter image description here

为什么会发生这种情况?以及如何解决?

+2

因为'Grid'元素可以重叠,并且您的按钮在给定空间内水平居中 – dkozl

回答

-1

使用行定义,列定义以及用于按键设定能见度可以解决这个问题

-1

按钮给定的空间内被水平居中。 为了解决这个问题,我必须将保证金一倍:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var offset = this.top1.ActualWidth + this.top2.ActualWidth; 
    this.top2.Margin = new Thickness(0, 0, offset, 0); 
} 

但是,这是正确的,只有当TOP2不随其布局的边缘到达。如果top2部分偏离左边缘,那么我们不需要将边距加倍。 top2的左侧和右侧都被修剪。