<Window x:Class="exSplitter.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">
<Window.Resources>
<!--GridSplitter样式-->
<Style x:Key="GridSplitterPreviewStyle">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Fill="#80000000"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="GridSplitterStyle1" TargetType="{x:Type GridSplitter}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="PreviewStyle" Value="{StaticResource GridSplitterPreviewStyle}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridSplitter}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
<Button Name="btnExpend" Content=":" VerticalAlignment="Center" Height="50" Panel.ZIndex="0" Cursor="Hand"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid Name="grdWorkbench">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.282*"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="0.718*"/>
</Grid.ColumnDefinitions>
<Grid Name="grd1" Margin="0" Background="#FFD8D8D8"/>
<GridSplitter x:Name="gsSplitterr" Grid.Column="1" HorizontalAlignment="Stretch" Margin="0" Background="#FF9F9F9F" Style="{DynamicResource GridSplitterStyle1}"/>
<Grid Name="grd2" Grid.Column="2" Margin="5,0,-5,0" Background="#FFEBF5F7"/>
</Grid>
</Window>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace exSplitter
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
GridLength m_WidthCache;
public MainWindow()
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
void MainWindow_Loaded(object sender, RoutedEventArgs e)
//获取GridSplitterr的cotrolTemplate中的按钮btn,必须在Loaded之后才能获取到
Button btnGrdSplitter = gsSplitterr.Template.FindName("btnExpend", gsSplitterr) as Button;
if (btnGrdSplitter != null)
btnGrdSplitter.Click += new RoutedEventHandler(btnGrdSplitter_Click);
void btnGrdSplitter_Click(object sender, RoutedEventArgs e)
GridLength temp = grdWorkbench.ColumnDefinitions[0].Width;
GridLength def = new GridLength();
if (temp.Equals(def))
//恢复
grdWorkbench.ColumnDefinitions[0].Width = m_WidthCache;
//折叠
m_WidthCache = grdWorkbench.ColumnDefinitions[0].Width;
grdWorkbench.ColumnDefinitions[0].Width = def;
代码:https://files.cnblogs.com/kooleven/exSplitter.rar