首页 > 解决方案 > 如何计算在 WPF 应用程序的主窗口函数中分配了文本的文本框的总高度

问题描述

在我的应用程序中,堆栈面板有十个子文本框。我在 c# 脚本的主窗口函数中将文本分配给文本框。我想计算文本框的总高度。

问题是它给出了 0。请查看下面的代码:

List<TextInfoData> newList = new List<TextInfoData>();

public MainWindow()
{
    InitializeComponent();

    for (int num = 0; num < 10; num++)
    {
        newList.Add(new TextInfoData("Sunset is the time of day when our sky meets the " +
            "outer space solar winds. There are blue, pink, and purple swirls, spinning " +
            "and twisting, like clouds of balloons caught in a blender.", 1));
    }

    RearrangeTextData(newList);
}

private void RearrageTextData(List<TextInfoData> textInfoData)
{

    TextBox tbox = new TextBox();
    //rest of code to define textbox margin and setting textwrapping to wrap

    double totalTextBoxHeight = 0;

    foreach (TextInfoData tinfoData in textInfoData)
    {
        tbox.Text = tinfoData.GetTextDataString();
        totalTextBoxHeight += tbox.ActualHeight;
        rootStackPanel.Children.Add(tbox);
    }

    MessageBox.Show("Total Height: " + totalTextBoxHeight);
}

我有一个 TextInfoData 类,它接受字符串和整数两个值作为参数。有函数GetTextDataString,它返回字符串值。

父堆栈面板的名称是 rootStackPanel。

如果我检查 rootStackPanel 的子项总数,它显示十个(这是正确的)但是当我尝试获取总文本框高度时,它给出 0。请指导我。

标签: c#wpf

解决方案


检查这篇文章:确定 WPF 文本块高度

计算可能是这样的:

private double GetHeight()
{
   double height = 0;
   foreach (var item in rootStackPanel.Children as IEnumerable)
   {
      if (item is TextBox tb)
      {
         tb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
         height += tb.DesiredSize.Height;
      }
   }
   return height;
}

希望有帮助。

其实我在这里又找到了一篇帖子。


推荐阅读