How to Find Reference to Dynamically Added Xamarin.Forms Element

72 Views Asked by At

In Xamarin.Forms we want to add a new button using

    f001content = new Xamarin.Forms.AbsoluteLayout;
    f001content.Children.Add(new Button
        {
            Text = "Button",
            AutomationId = "MyButton",
        }, new Rectangle(0,0,100,40));

How can we find the reference to the button just added so that we can modify it in the future?

2

There are 2 best solutions below

0
Andrew On

If you're doing in the code behind, you need to create a variable to hold it.

var coolButton = new Button { Text = "Button", AutomationId = "MyButton" };
f001content.Children.Add(coolButton, new Rectangle(0,0,100,40));

Now when you need to reference it, you can. Note that you'll most likely want coolButton to be class wide or something. If you declare it in a method, you'll lose the reference when you exit the method.

0
Jason On

Create a reference to it

f001content = new Xamarin.Forms.AbsoluteLayout;

var btn = new Button
    {
        Text = "Button",
        AutomationId = "MyButton",
    }, new Rectangle(0,0,100,40));

 f001content.Children.Add(btn);

If you need to reference it outside the scope it’s created in, you’ll need to declare it at the class level