如何计算在WPF应用程序的主窗口函数中分配文本的文本框的总高度

问题描述 投票:0回答:1

在我的应用程序中,有十个文本框子框架。我在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,它返回字符串值。

父堆栈面板的名称是根StackPanel。

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

c# wpf
1个回答
0
投票

看看这篇文章:Determine WPF Textblock Height

计算可能是这样的:

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

希望有所帮助。

其实我发现了一个帖子here

© www.soinside.com 2019 - 2024. All rights reserved.