WPF - TextBlock问题

时间:2011-04-01 18:44:12

标签: wpf

我有一个TextBlock控件定义如下:

<TextBlock Width="250"
           Height="23"
           HorizontalAlignment="Left"
           VerticalAlignment="Top" 
           Margin="20,16,0,0"
           Name="RecipeName"
           Text="{Binding Recipe.RecipeName}"/>

我希望TextBlock计算显示整个文本所需的宽度,而不是硬编码250的宽度。我认为有办法做到这一点?

2 个答案:

答案 0 :(得分:5)

如果未设置Width,它通常应自动适合内容。要获得此自动宽度,请使用ActualWidth属性。

明确告诉控件使用自动调整大小

Width="Auto"

实际的大小调整行为还取决于HorizontalAlignment属性,如果它设置为Stretch,则控件将适合内容而非容器。

另见MSDN


编辑:某些可视化:

<TextBlock Text="SetLeft"     Width="200"  HorizontalAlignment="Left"     Background="Yellow"/>
<TextBlock Text="SetCenter"   Width="200"  HorizontalAlignment="Center"   Background="Yellow"/>
<TextBlock Text="SetStretch"  Width="200"  HorizontalAlignment="Stretch"  Background="Yellow"/>
<TextBlock Text="AutoLeft"    Width="Auto" HorizontalAlignment="Left"     Background="Yellow"/>
<TextBlock Text="AutoCenter"  Width="Auto" HorizontalAlignment="Center"   Background="Yellow"/>
<TextBlock Text="AutoStretch" Width="Auto" HorizontalAlignment="Stretch"  Background="Yellow"/>
<TextBlock Text="OmitLeft"                 HorizontalAlignment="Left"     Background="Yellow"/>
<TextBlock Text="OmitCenter"               HorizontalAlignment="Center"   Background="Yellow"/>
<TextBlock Text="OmitStretch"              HorizontalAlignment="Stretch"  Background="Yellow"/>

enter image description here

答案 1 :(得分:2)

如果删除“宽度”设置,则其大小取决于它的父级。如果您发布周围的XAML,这将有助于确定大小调整行为。