在我的 WPF 窗口(.NET 4.0)中,我有两列网格:左侧的拉伸文本框(或其他)和右侧的扩展器。同样在 Expander 我有 GridSplitter,它旨在在 Expander 展开时调整左右列的大小。但它不起作用。
这是我的 XAML 代码:
<Window x:Class="WpfApplication10.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 ShowGridLines="True" >
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" Name="column"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" HorizontalAlignment="Stretch" TextWrapping="Wrap"
Text="TextBox" VerticalAlignment="Stretch" Background="Aqua"/>
<Expander Grid.Column="1" Header="Expander" ExpandDirection="Left"
HorizontalAlignment="Right" Background="LightBlue" >
<Expander.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Some text Some text Some Text" Grid.Column="1"/>
<GridSplitter Grid.Column="0" Width="5"
ResizeBehavior="PreviousAndCurrent"
ResizeDirection="Columns"
HorizontalAlignment="Stretch"/>
</Grid>
</Expander.Content>
</Expander>
</Grid></Window>
找到了合适的解决方案。XAML:
<Window x:Class="WpfApplication10.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>
<BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
</Window.Resources>
<Grid ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" Name="leftColumn"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" Name="rightColumn" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0"
HorizontalAlignment="Stretch"
TextWrapping="Wrap"
Text="TextBox"
VerticalAlignment="Stretch"
Background="Aqua" />
<Expander Grid.Column="2"
Name="Expander"
Header="Expander"
ExpandDirection="Left"
Background="LightBlue"
Collapsed="Expander_Collapsed"
Expanded="Expander_Expanded" >
<TextBlock Text="Some text Some text Some Text" />
</Expander>
<GridSplitter Grid.Column="1"
Width="5"
ResizeBehavior="PreviousAndNext"
ResizeDirection="Columns"
VerticalAlignment="Stretch"
Height="Auto"
Visibility="{Binding ElementName=Expander, Path=IsExpanded,
Converter={StaticResource BoolToVisConverter}}"/>
</Grid></Window>
代码隐藏:
private void Expander_Collapsed(object sender, RoutedEventArgs e)
{
leftColumn.Width = new GridLength(1, GridUnitType.Star);
rightColumn.Width = new GridLength(1, GridUnitType.Auto);
}
private void Expander_Expanded(object sender, RoutedEventArgs e)
{
rightColumn.Width = new GridLength(1, GridUnitType.Star);
}