Wpf 如何使StackPanel的宽度与其内容相同?
以下模板在彩色框中显示动态信息 但是,框始终是DockPanel/屏幕的全宽 我可以在Border元素中添加一个固定宽度,但是很长的客户名称可能会被删除 如何告诉边框它应该根据内容的宽度来扩展和收缩宽度,就像HTML中的Wpf 如何使StackPanel的宽度与其内容相同?,wpf,xaml,stackpanel,Wpf,Xaml,Stackpanel,以下模板在彩色框中显示动态信息 但是,框始终是DockPanel/屏幕的全宽 我可以在Border元素中添加一个固定宽度,但是很长的客户名称可能会被删除 如何告诉边框它应该根据内容的宽度来扩展和收缩宽度,就像HTML中的元素那样? HTML: <table> <tr> <td style="background-color: #eee; padding: 5px"> the table will be as wi
元素那样?
HTML:
<table>
<tr>
<td style="background-color: #eee; padding: 5px">
the table will be as wide as this text
</td>
</tr>
</table>
<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>
这张桌子将和这篇课文一样宽
XAML:
<table>
<tr>
<td style="background-color: #eee; padding: 5px">
the table will be as wide as this text
</td>
</tr>
</table>
<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>
最简单的方法是设置边框的HorizontalAlignment=“Center”(或左对齐,或右对齐,以您喜欢的布局为准)