2017-02-21 109 views
0

我剛開始使用WPF(而不是winforms),並試圖創建一個固定大小的窗口(請參見圖像)。匹配網格和窗口大小WPF

image 1

問題是,每當我運行應用程序右下角被搞砸了,有附近的按鈕和邊緣之間的零空間。 (見其他圖)

image 2

這裏是XAML代碼(大多是由Visual Studio設計產生)

<Window x:Class="UseCaseHelper.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:UseCaseHelper" 
     mc:Ignorable="d" 
     Title="UseCaseHelper" Height="500" Width="900"> 
    <Grid> 
     <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75"/> 
     <Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="809,441,0,0" VerticalAlignment="Top" Width="75"/> 

    </Grid> 
</Window> 

我試過google搜索沒有成功的解決方案。希望有人能夠指出我在這裏做錯了什麼。

+0

爲兩者使用Margin =「10」,設置VerticalAlignment = Top/Bottom和Horizo​​ntalAlignment = Left/Right。 – AnjumSKhan

回答

1

我總是在這些設置中發現DockPanel更靈活。您可以將DockPanel.Dock設置爲LeftRightBottomTop,而不是您設置的VerticalAlighnment和Margin。

<DockPanel LastChildFill="False"> 
     <Button DockPanel.Dock="Top" 
       Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" 
       Width="75"/> 
    <Button DockPanel.Dock="Bottom" 
      Content="Button" HorizontalAlignment="Right" Margin="0,0,10,10" Width="75"/> 
</DockPanel> 

請注意,您也可以對兩個按鈕使用Margin =「10」。

但是,如果你想使用網格,可以用以下結構:

<Grid> 
    <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0" 
      Width="75"/> 
    <Button Content="Button" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,10,10" Width="75"/> 
</Grid> 

注意,在這種情況下,如果窗口足夠小,他們會重疊。

另一種選擇是增加RowDefinitionsColumnDefinitions到網格:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="*"/> 
     <RowDefinition Height="Auto"/> 
    </Grid.RowDefinitions> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="Auto"/> 
     <ColumnDefinition Width="*"/> 
     <ColumnDefinition Width="Auto"/> 
    </Grid.ColumnDefinitions> 
    <Button 
      Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0" 
      Width="75"/> 
    <Button Grid.Column="2" Grid.Row="2" 
     Content="Button" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,10,10" Width="75"/> 
</Grid> 

它的性能比較是比其他兩個更好,如果窗口是非常小的。

+0

謝謝!使用DockPanel和給定的邊距工作。 – Viva