2016-11-08 120 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> 

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