在WPF中将展开器(Expander)垂直排列显示

6
考虑有两个可扩展控件一个放在另一个下面。如果一个可扩展控件被折叠,那么实际间隔(在扩展时)必须减小,并且另一个可扩展控件必须在第一个可扩展控件下方显示,没有间隙(在第一个和第二个可扩展控件之间)。如果第一个可扩展控件被展开,则必须调整并显示第二个控件。如何实现?
4个回答

14
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <Expander>
        <TextBlock Text="expander 1 content" />
    </Expander>
    <Expander Grid.Row="1">
        <TextBlock Text="expander 2 content" />
    </Expander>
</Grid>

当行高设置为“自动”时,行高会自动调整以适应内容。这意味着第一行的行高会随着您展开/折叠第一个展开器而增加或缩小。


2
如果您只想要两个可扩展的控件,并且当一个控件展开时,另一个控件会折叠,则只需将它们的IsExpanded属性绑定在一起,使其中一个与另一个相反即可。
<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication4="clr-namespace:WpfApplication4"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <WpfApplication4:NotConverter x:Key="notConverter"/>
</Window.Resources>

<StackPanel Margin="12">
    <Expander Header="First" IsExpanded="{Binding IsExpanded, ElementName=expander2, Converter={StaticResource notConverter}}">
        <TextBlock Text="Hello"/>
    </Expander>
    <Expander Header="Second" Name="expander2">
        <TextBlock Text="World!"/>
    </Expander>
</StackPanel>
</Window>

NotConverter.cs

public class NotConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !((bool)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !((bool)value);
    }
}

1
使用 Orientation="Vertical"StackPanel 作为包装器。这应该会有所帮助。

0

你可以按照Eirik的建议去做,或者将你的可扩展面板放在一个StackPanel上,并指定可扩展面板的网格高度。这里有一系列包含两个视频的教程,将更好地帮助你学习WPF中的可扩展面板。 https://www.youtube.com/watch?v=ajKPYZ1KZc4&list=PLWTyZJ_llht1-OGaFaG-6D-0vjW_V0rpg

<StackPanel  Height="768" Width="500" HorizontalAlignment="Left">
        <Expander Header="Expande me" Background="Chocolate" FontSize="25">
            <Grid Height="200" Background="AntiqueWhite" Width="500">
                <Label Content="yay" Background="Aqua" Height="40" Width="90"/>
            </Grid> 
        </Expander>

        <Expander Header="Me too" Background="MediumAquamarine" FontSize="20">
            <Grid Height="200" Width="500" Background="Coral">
                <Label Content="Yay!!" Height="40" Width="100" Background="Khaki"/>
            </Grid>
        </Expander>
    </StackPanel>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接