简体   繁体   中英

How to Find Reference to Dynamically Added Xamarin.Forms Element

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM