WPF中Grid(网格)的GridSplitter(网格分割)

时间:2024-04-08 11:28:38

如果在WPF中的Grid中加入GridSplitter(网格分割条),以下是最佳实践。

  • 分配整个一行或者一列给分割条,并把行高或者列宽设置为Auto
  • 使用Grid.RowSpan或者Grid.ColumnSpan以让它撑满这个网格的全高或者全宽
  • 为了使分割条看得更能清楚
    1. 设定它的宽度或者高度为一些足以看到的值,例如5
    2. 设置这个GridSplitter的Background属性为更显眼的颜色
  • 设置这个GridSplitter的VerticalAlignment和HorizontalAlignment属性(这个是容易忽略的一点)
  1. VerticalSplitter: VerticalAlignment=Stretch, HorizontalAlignment=Center
  2. HorizontalSplitter: VerticalAlignment=Center, HorizontalAlignment=Stretch


实例代码:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
 
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
 
        <Button Margin="5">Button 1</Button>
        <Button Grid.Row="0"
                Grid.Column="2"
                Margin="5">Button 2</Button>
        <Button Grid.Row="2"
                Grid.Column="0"
                Margin="5">Button 3</Button>
        <Button Grid.Row="2"
                Grid.Column="2"
                Margin="5">Button 4</Button>
 
        <GridSplitter Grid.Row="1"
                      Grid.Column="0"
                      Grid.ColumnSpan="3"
                      Height="5"
                      Background="Red"
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Center" />
 
        <GridSplitter Grid.Row="0"
                      Grid.Column="1"
                      Grid.RowSpan="3"
                      Width="5"
                      Background="Blue"
                      VerticalAlignment="Stretch"
                      HorizontalAlignment="Center" />
    </Grid>
</Window>


分割效果展示:

WPF中Grid(网格)的GridSplitter(网格分割)


WPF中Grid(网格)的GridSplitter(网格分割)


WPF中Grid(网格)的GridSplitter(网格分割)