【问题标题】:How to set dynamic height of UIElement based on the content in text block如何根据文本块中的内容设置 UIElement 的动态高度
【发布时间】:2015-06-28 04:59:20
【问题描述】:

我需要根据内容设置 UiElement 的高度。我将内容设置为文本块并将文本块 MaxWidth 设置为某个值,MaxHeight 为 double.MaxValue。现在我将此文本块设置为边框的子项。nowi 像下面一样测量边框

textBlock.MaxWidth=200;
textBlock.MaxHeight=double.MaxValue;
var area=new Border{child=textBlock};
area.Measure(new size(textBlock.MaxWidth,textBlock.MaxHeight));
var r=area.DesiredSize;

但上面的代码为不同宽度的文本块给出了不正确的期望大小。有没有其他方法可以根据文本内容计算高度。

【问题讨论】:

    标签: c# wpf xaml wpf-controls uielement


    【解决方案1】:

    使用下面的

    <ViewBox Width="200">
     <TexBlock Text="..." ... />
    </ViewBox>
    

    它将调整 TextBlock 大小以始终具有该宽度的矩形。

    试着告诉我它是否适合你的情况

    【讨论】:

      【解决方案2】:

      我认为您实际上是在寻找名为 StackPanel 的 WCF 控件,但我也会提供代码以通过编程方式更改高度。

      在 XAML 中使用 StackPanel:

      <StackPanel Width="200">
          <Border BorderThickness="1" BorderBrush="Black">
              <TextBlock TextWrapping="Wrap" Text="This TextBlock will be 
                  wrapped by a black Border that has the height of the TextBlock
                  and with it's Width provided from the StackPanel"/>
          </Border>
      </StackPanel>
      

      或以编程方式更改 TextBlock 高度:

      <Border x:Name="border" BorderBrush="Black" BorderThickness="1" Height="100" Width="200">
          <TextBlock x:Name="textBlock" Background="Black" Width="40" Height="40"/>
      </Border>
      

      然后你的代码就是:border.Height = textBlock.Height;

      【讨论】:

        【解决方案3】:
         <Border Width="300" BorderThickness="1" BorderBrush="Black">
            <TextBlock Text="welcome" Foreground="Blue"/>
            </Border>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-07
          • 2015-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          相关资源
          最近更新 更多