在Grid或StackPanel的有限空间中使用TextTrimming的按钮

时间:2014-08-19 13:09:48

标签: wpf xaml grid resize stackpanel

我正在尝试构建一行按钮,这些按钮将在正常状态下保持对齐,并且当容器提供的空间不再足够正常大小时,它会均匀收缩。

如果有足够的空间,StackPanel的行为方式正确: enter image description here

如果没有足够的空间,带有星号列的Grid提供了我想要的东西: enter image description here

如何使用一个布局容器完成两种状态?

我的xaml:

<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="500">

    <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="5"/>
            <Setter Property="Padding" Value="3"/>
            <Setter Property="VerticalAlignment" Value="Top"/>
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock TextTrimming="CharacterEllipsis" Text="{TemplateBinding Content}"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button Grid.Column="0" Content="Save As" />
            <Button Grid.Column="1" Content="Copy" />
            <Button Grid.Column="2" Content="Exit Application" />
        </Grid>

        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <Button Content="Save As" />
            <Button Content="Copy" />
            <Button Content="Exit Application" />
        </StackPanel>

    </Grid>
</Window>

编辑:Novitchi的建议(Horizo​​ntalAlignment左侧为网格)几乎有效:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以尝试将网格水平对齐到左侧:

        <Grid HorizontalAlignment="Left">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button Grid.Column="0" Content="Save As" />
            <Button Grid.Column="1" Content="Copy" />
            <Button Grid.Column="2" Content="Exit Application" />
        </Grid>