在Xamarin Forms后面的代码中访问以前创建的组件

问题描述 投票:0回答:1

所以,我正在做一个xamarin形式的应用程序,当单击一个按钮时,它会创建一些组件和布局。我的问题是,我以后需要访问这些组件,以便可以更改某些标签中的文本,从编辑器中获取值,然后在必要时将其删除...

这是我创建组件的代码:

private void newItem()
        {
            StackLayout add = new StackLayout { };

            add.StyleId = "add_" + posicio;

            elements.Children.Add(add);

            StackLayout grupInical = new StackLayout { Orientation = StackOrientation.Horizontal };
            add.Children.Add(grupInical);


            Label number= new Label { VerticalOptions = LayoutOptions.End, HorizontalOptions = LayoutOptions.StartAndExpand, Text = "Element " + posicio.ToString(), FontAttributes = FontAttributes.Bold, Margin = new Thickness(5, 0, 0, 0) };
            Button tancar = new Button { Padding = new Thickness(5), Text = "✕", HorizontalOptions = LayoutOptions.End, BackgroundColor = Color.Transparent, WidthRequest = 30, HeightRequest = 30 };
            number.StyleId = "number_" + posicio;
            tancar.StyleId = "tancar_" + posicio;
            tancar.Clicked += Eliminar_clicked;

            grupInical.Children.Add(number_);
            grupInical.Children.Add(tancar);


            StackLayout values = new StackLayout { Orientation = StackOrientation.Horizontal };
            values.StyleId = "values" + posicio;
            add.Children.Add(values);

            Button elegir = new Button { Text = "Element" , };
            Editor percentatge = new Editor { MaxLength = 2, WidthRequest = 30 };
            Label desc = new Label { VerticalOptions = LayoutOptions.Center, FontSize = 20, FontAttributes = FontAttributes.Bold, Text = "%" };
            Picker picker = new Picker {IsVisible = false };
            elegir.Clicked += Elegir_Clicked;
            elegir.StyleId = "elegir_"+posicio;
            percentatge.StyleId = "percentatge_" + posicio;
            desc.StyleId = "desc_" + posicio;
            picker.StyleId = "picker_" + posicio;

            values.Children.Add(elegir);
            values.Children.Add(percentatge);
            values.Children.Add(desc);
            values.Children.Add(picker);
            posicio += 1;
            scroll.ScrollToAsync(0, elements.Height, true);
        }

如您所见,我正在尝试通过为它们分配styleid值来访问组件,但是由于此标记未达到此目标,因此我无法访问该组件。

您对如何识别物品有任何疑问,以便以后参考?

c# android xaml xamarin.forms code-behind
1个回答
0
投票

在类级别上声明这些组件,然后可以在项目的其他位置访问它们。

public partial class MainPage : ContentPage
{

    Label numberLabel;
    StackLayout myAddStackLayout;

    public MainPage()
    {
        InitializeComponent();

        newItem()

        numberLabel.Text = "updateValue";

        myAddStackLayout.Children.Add(...);
    }

    public void test() {

        numberLabel.Text = "updateValue";

        myAddStackLayout.Children.Add(...);
    }

    private void newItem()
    {
        StackLayout add = new StackLayout { };
        Label number = new Label ();          
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.