Wpf C# 获取程序添加的按钮的实际高度

Hui Liu-MSFT 41,146 信誉分 Microsoft 供应商
2024-04-30T08:20:48.3566667+00:00

我有一个代码。我想从以编程方式添加的所有按钮中获取高度,但所有高度的结果均为 0。你能帮帮我吗?

int k = 1;
int indexMax = 100;
Double[] vyska = new double[1000];

private void btnOpen_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < indexMax + 1; i++)
{
var btn = new Button()
{
Content = i.ToString() + " " + textEnSRT[i] + " ",
HorizontalAlignment = HorizontalAlignment.Right,
Foreground = new SolidColorBrush(Colors.Black) { Opacity = 0.9 },
Background = new SolidColorBrush(Colors.LightGray) { Opacity = 0.4 },
BorderThickness = new Thickness(0, 0, 0, 0),
Margin = new Thickness(0, 2, 4, 0),
Tag = i,
FontSize = 16,
};
btn.Click += Btn_Click;
stackPanel1.Children.Add(btn);
}



        foreach (Button bt in FindVisualChildren<Button>(stackPanel1))
        {
            vyska[k] = bt.ActualHeight;           
         }
    }
private void btnHladaj_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 10; i++)
{
MessageBox.Show(vyska[i].ToString()); //Every is zero.
}
}

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}

Note:此问题总结整理于:Wpf C# get ActualHeight of the button added by program

Windows Presentation Foundation
Windows Presentation Foundation
.NET Framework 的一部分,它提供统一的编程模型,用于在 Windows 上构建业务线桌面应用程序。
65 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Jiale Xue - MSFT 35,556 信誉分 Microsoft 供应商
    2024-04-30T11:03:06.72+00:00

    请将数组设置为如下:

     foreach (Button bt in FindVisualChildren<Button>(stackPanel1))  
                {  
                    vyska[k] = bt.ActualHeight;  
                    k++;  
                }  
    

    因为我们需要为数组的每个元素分配一个值。

    结果: 29555-1.png


    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。

    注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助