如何让StackPanel只与其内容一样宽?

时间:2009-06-18 11:16:34

标签: wpf xaml stackpanel

以下模板在彩色框中显示动态信息

但是,该框始终是DockPanel /屏幕的全宽。

我可以在Border元素中加上固定宽度,但是很长的客户名称可能会被切断。

如何告诉Border它应该根据其内容的宽度扩展和收缩宽度,例如HTML中的<table>元素?

HTML:

<table>
    <tr>
        <td style="background-color: #eee; padding: 5px">
            the table will be as wide as this text
        </td>
    </tr>
</table>

XAML:

<Window.Resources>
    <DataTemplate x:Key="CustomerTemplateShow">
        <Border CornerRadius="5" Background="#eee" Padding="5">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text=" "/>
                <TextBlock Text="{Binding LastName}"/>
            </StackPanel>
        </Border>
    </DataTemplate>
</Window.Resources>

<DockPanel LastChildFill="False" Margin="10">
    <ContentControl 
        DockPanel.Dock="Top"
        Content="{Binding SelectedCustomer}" 
        ContentTemplate="{StaticResource CustomerTemplateShow}"/>
</DockPanel>

1 个答案:

答案 0 :(得分:2)

最简单的方法是设置Border的Horizo​​ntalAlignment =“Center”(或左侧或右侧,无论您喜欢哪种布局)。