【C#/WPF】GridSplitter 分割布局,拖拽控件分隔栏以改变控件尺寸

原文: 【C#/WPF】GridSplitter 分割布局,拖拽控件分隔栏以改变控件尺寸

需求:界面由多部分控件组成,想要拖拽控件之间的分隔栏以改变尺寸。

MainWindow.xaml:

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

    <ListBox Grid.Row="0" Grid.Column="0">
        <ListBoxItem>aaaa</ListBoxItem>
        <ListBoxItem>bbbb</ListBoxItem>
        <ListBoxItem>cccb</ListBoxItem>
    </ListBox>

    <TextBlock Grid.Row="0" Grid.Column="1">sadfas</TextBlock>

    <GridSplitter Grid.Row="0" Grid.Column="0" Width="0" VerticalAlignment="Stretch" HorizontalAlignment="Right"/>

</Grid>

运行效果如下:

红色虚线表示了拖动分隔栏以改变控件的尺寸边缘。

分隔栏往左拖动

分隔栏往右拖动

坑点:

  • 必须使用Grid及其行和列来定义,否则能显示但无法拖动。例如下面的写法是无效的:
<StackPanel Orientation="Horizontal">
    <TextBlock Text="LLLLLLLLLLLLLL"/>
    <GridSplitter Width="10" HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="Wheat"/>
    <TextBlock Text="RRRRRRRRRRRRRR"/>
</StackPanel>
  • 对于左右分割列,必须指定分隔栏GridSplitter的宽度Width,以及设置VerticalAlignment,否则无效。
  • 对于上下分割行,必须指定分隔栏GridSplitter的高度Height,以及设置HorizontalAlignment,否则无效。

再来一个详细一点的例子:

<Window x:Class="WpfApplication1.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:WpfApplication1"
        xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="1000">

    <Grid>
        <Grid.RowDefinitions/>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="0" Grid.Column="0" Text="LLLLLLLLLLLLLL"/>
        <GridSplitter Grid.Row="0" Grid.Column="1" Width="10" HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="Wheat"/>

        <Grid Grid.Row="0" Grid.Column="2">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="10"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Row="0" Grid.Column="0" Text="RRRRRRTTTTTTTT"/>
            <GridSplitter Grid.Row="1" Grid.Column="0" Height="10" HorizontalAlignment="Stretch" Background="Wheat"/>
            <TextBlock Grid.Row="2" Grid.Column="0" Text="RRRRRRBBBBBBBB"/>

        </Grid>       
    </Grid>

</Window>

运行效果如图:下面的水平和垂直的黄色分隔栏都是可以拖动的。
这里写图片描述

重要的参考:

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12741774.html