如何使StackPanel仅与其内容一样宽?

时间:2022-12-04 19:38:47

The following template shows dynamic information in a colored box.

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

However, the box is always the full width of the DockPanel/screen.

但是,该框始终是DockPanel /屏幕的整个宽度。

I could put a fixed Width in the Border element, but then a very long customer name might get cut off.

我可以在Border元素中放置一个固定的Width,但是很长的客户名称可能会被切断。

How can I tell the Border that it should expand and contract its width based on width of its content, something like a <table> element does in HTML?

我怎么能告诉Border它应该根据其内容的宽度扩展和收缩它的宽度,就像HTML中的

元素一样?

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 个解决方案

#1


The simplest way is to set the Border's HorizontalAlignment="Center" (or Left, or Right, whichever you prefer for your layout).

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

#1


The simplest way is to set the Border's HorizontalAlignment="Center" (or Left, or Right, whichever you prefer for your layout).

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