Home > Mobile >  How to Find Reference to Dynamically Added Xamarin.Forms Element
How to Find Reference to Dynamically Added Xamarin.Forms Element

Time:11-30

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related