Is it a bug in Xamarin StackLayout children.Add, Clear function?

152 Views Asked by At

When creating a button statically, there is no problem in clearing and adding the stacklayout. However, there is a problem when dynamically creating a button and clearing and adding it.

Is there anything I need to do separately when creating dynamically? Do I have to create the layout itself in code too?

I don't understand. This is like a bug.

<ContentView x:Name="xMainContentsView" Grid.Row="1" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

            <ScrollView Orientation="Horizontal" HorizontalOptions="FillAndExpand">
                <StackLayout x:Name="xView" Margin="35,80,35,80" Spacing="25" Orientation="Horizontal" HorizontalOptions="FillAndExpand">
                    <Button Text="g02" Clicked="Button_Clicked"></Button>                   
                </StackLayout>
            </ScrollView>
            
            <!--<StackLayout x:Name="xPageView"  Orientation="Horizontal" HorizontalOptions="FillAndExpand">
            </StackLayout>-->
</ContentView>


private void Button_Clicked(object sender, EventArgs e)
        {
            xView.Children.Clear();
            xView.Children.Add(new Spectrum(this));
        }




private void InitializeCompView()
        {
              
            foreach (MainViewMeasureType contents in Enum.GetValues(typeof(MainViewMeasureType)))
            {
                CtrlButton button = new CtrlButton
                {
                    WidthRequest = 180,
                    HeightRequest = 180,
                    Text = contents.ToString(),
                    ClassId = contents.ToString(),
                };
                button.Pressed += BtnMainContentClick;

                xView.Children.Add(button);
            } 
        }
        



private void BtnMainContentClick(object sender, EventArgs e)
        {
            xView.Children.Clear();
            xView.Children.Add(new Spectrum(this));
        }
1

There are 1 best solutions below

0
Liyun Zhang - MSFT On

I have created a sample to test the StackLayout children.Add, Clear function and met the same problem.

In addition, the exception message mentioned the FasterRender and then I disabled it in the mainactivity. But the same exception came, so I change the button.Pressed += BtnMainContentClick; to button.Clicked += BtnMainContentClick;. It worked well.

So you can also try this and report this as a bug to the xamarin on the github.