EssVee
EssVee

Reputation: 93

How to get content of programatically created dynamic buttons in WPF?

I am trying to pass content of a button to another class and these buttons are created dynamically which means the contents are different. When I try to access button.content it says I can't access the cause it doesn't exist in current context.

I have this this code in a method 1 which I run in class A.

foreach (string lines in textfile)
    {
        if (Checker == CheckerCounter)
        {
            marginbottom += 150;
            left = 0;
        }
        string threeletters = additional.Substring(0, 3);
        if (additional.Contains(passedinfoArray[2]))
        {
             Button DynamicBtn = new Button
            {

                Content = threeletters,
                Width = 100,
                Height = 56,
                Foreground = new SolidColorBrush(Colors.White),
                Background = new SolidColorBrush(Colors.Black),
                FontSize = 24,
                Margin = new Thickness(-900 + left, 0, 0, 400 - marginbottom),


            };

            left += 300;
            DynamicChecker += 1;
            Maingrid.Children.Add(DynamicBtn);
            DynamicButton1.Click += new System.Windows.RoutedEventHandler(DynamicBtn_Click);

The routed method 2 is also in class A.

 private void DynamicBtn_Click(object sender, RoutedEventArgs e)
    {

         Array[0] = DynamicBtn1.Content; //code that doesnt work
        classB bClass = new classB(Array);
        this.Close();
        bClass.ShowDialog();
    }

I need the clicked button's content to be stored into an array as a string which already have been created but I can't dynamically access the content of the clicked button.

How do I go about this?

Upvotes: 3

Views: 131

Answers (1)

Nkosi
Nkosi

Reputation: 247008

Since the button is the one raising the event then just cast the sender to the desired type.

private void Dynamicbutton1_Click(object sender, RoutedEventArgs e) {
    var DynamicButton1 = sender as Button;//this casts the sender to the desired type
    passedinfoArray[0] = DynamicButton1.Content as string; //Or DynamicButton1.Content.ToString();
    classB bClass = new classB(passedinfoArray);
    this.Close();
    showTour.ShowDialog();
}

Upvotes: 4

Related Questions