1

我正在动态添加 TextBlocks,但我遇到了高度问题。

有时文本会出现剪切。此外,似乎应用程序为所有元素分配了相同的高度。

xml:

<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);

演示: 演示

4

1 回答 1

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>

在此处输入图像描述

于 2013-11-06T00:48:47.643 回答