2016-11-08 122 views
0

我在我的WPF應用程序中有一個網格,它當前是水平和垂直居中,沒有什麼大不了的。但是,我想根據單個網格單元而不是整個網格將我的整個網格居中。這可能嗎?這是我想要實現的一個小例子。我希望紅十字會成爲中心。 enter image description here 第一張圖片顯示整個網格(網格是綠色正方形)居中,第二張圖片顯示整個網格根據紅十字單元居中。這在XAML中可能嗎?我沒有特意提供任何代碼,因爲我不認爲這對於這個問題是必要的,它不是像我有一個錯誤或什麼不工作,我只是不知道如何實現這一點。中心網格根據WPF中的網格單元格

+0

所以,你想紅十字會是在畫面的中心,對不對?不是包含該單元的整個網格,而是單元本身。 –

+0

@LupuSilviu我做了一個更新,希望現在更有意義? – Markinson

+0

也許如果你解釋你想要解決什麼問題,而不是如何實現這個特定的解決方案,人們將能夠提供更好的答案(以及更好的整體解決方案)。那麼這個佈局的目的是什麼? – ndonohoe

回答

2

有外網格,內網格和元素應該居中。外部和內部網格具有相同的行和列權重。佈局適應調整

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*"/> 
     <RowDefinition Height="2*"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

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

    <Grid Grid.Column="1" Grid.ColumnSpan="3" 
      Background="LightGray" 
      Grid.Row="0" Grid.RowSpan="2"> 

     <Grid.ColumnDefinitions> 
      <ColumnDefinition/> 
      <ColumnDefinition/> 
      <ColumnDefinition/> 
     </Grid.ColumnDefinitions> 

     <Grid.RowDefinitions> 
      <RowDefinition /> 
      <RowDefinition /> 
      <RowDefinition /> 
     </Grid.RowDefinitions> 

     <Border Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" 
       Background="Green"/> 

     <Border Grid.Row="1" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="2" 
      Background="Cyan"/> 
    </Grid> 
</Grid> 

screen shot

0

我認爲你可以做到這一點的唯一方法,只有當你的UI組件具有固定的大小。這裏是我如何實現你所問的代碼示例。

<Window x:Class="StackStuff.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:StackStuff" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="350" Width="525"> 
<DockPanel> 
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center" Background="Red" 
      Width="150" Height="100" ClipToBounds="False"> 

     <Border Margin="0,-150,-30,0" BorderBrush="Black" BorderThickness="1" Height="50" 
       Width="180"> 
      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="50"/> 
        <ColumnDefinition Width="130"/> 
       </Grid.ColumnDefinitions> 

       <Border Grid.Column="0" BorderThickness="1" BorderBrush="Black"/> 
       <Border Grid.Column="1" BorderThickness="1" BorderBrush="Black"/> 

      </Grid> 
     </Border> 

     <Border Margin="0,0,-180,0" BorderBrush="Black" BorderThickness="1" 
       Width="30" Height="100"> 

     </Border> 
    </Grid> 
</DockPanel> 

正如你所看到的,它爲所有的細胞固定大小。