WPF TextBlock高度

时间:2013-11-06 00:09:55

标签: c# wpf windows-8 windows-store-apps textblock

我正在动态添加TextBlocks,但我的高度有问题。

有时文字会被剪切掉。此外,似乎应用程序为所有元素分配相同的高度。

xaml:

<ScrollViewer Grid.Column="2" x:Name="DetailInfoScroll"  
              Margin="25,0,50,0"
              Style="{StaticResource HorizontalScrollViewerStyle}">
    <VariableSizedWrapGrid Grid.Column="2" Margin="25,0,50,35" 
                           HorizontalAlignment="Left"  
                           VerticalAlignment="Center" 
                           x:Name="StkText">                      
    </VariableSizedWrapGrid>
</ScrollViewer>

和代码:

var txt = new TextBlock
{
    Text = text,
    TextWrapping = TextWrapping.Wrap,
    TextAlignment = TextAlignment.Justify,
    FontSize = 14,
    Margin = new Thickness(0, 0, 25, 15),
    MaxWidth = 400,
    LineStackingStrategy = LineStackingStrategy.MaxHeight,
    VerticalAlignment = VerticalAlignment.Center,
    HorizontalAlignment = HorizontalAlignment.Left
};

txt.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
var desiredSizeNew = txt.DesiredSize;
txt.Height = desiredSizeNew.Height;

StkText.Children.Add(txt);

演示: Demo

1 个答案:

答案 0 :(得分:1)

不确定这是否是完美的解决方案但是我找到了一种方法来使height属性不被锁定到该行中的列。这样做的问题是它会在将第一列放入第二列之前一直向下到第一列。没有简单的方法让WrapPanel在没有锁定同一行中的所有高度的情况下水平添加元素。

这也通过使用样式摆脱了你的代码。

以下是使用中的示例

<Window.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Width" Value="400"/>            
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="TextWrapping" Value="Wrap"/>  
        <Setter Property="Margin" Value="10"></Setter>
    </Style>
</Window.Resources>
<WrapPanel Orientation="Vertical" Width="850" Background="Black" Height="300" >
    <TextBlock Text="Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do."/>
    <TextBlock Text="Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers."/>
    <TextBlock Text="Questions that need improvement may be closed until someone fixes them."/>
    <TextBlock Text="All questions are tagged with their subject areas. Each can have up to 5 tags, since a question might be related to several subjects. Click any tag to see a list of questions with that tag, or go to the tag list to browse for topics that interest you."/>
    <TextBlock Text="Your reputation score goes up when others vote up your questions, answers and edits."/>        
</WrapPanel>

enter image description here