Wpf C# get ActualHeight of the button added by program

Blader 156 Reputation points
2020-09-30T15:43:19.713+00:00

I have a code bellow. I want to get heights from all buttons adding programmatically, but results for all heights is 0. Can you help me please?

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

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,496 Reputation points Microsoft Vendor
    2020-10-01T02:35:03.33+00:00

    Hi Blader-2347,

    Please set the array as the following:

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

    Because we need to assign a value to each element of the array.

    Result:
    29555-1.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our document to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful