12

I am just playing arround with .Net MAUI. I want to retrieve information from a Rest service and based on the result I want to add Buttons programmatically to a VerticalStackLayout. When I debug the solution the buttons are added to the VerticalStackLayout but the UI is not updated.

Here the code Snippet

var btn = new Button(); btn.Text = "Button " + count + " added"; btn.Clicked += OnCounterClicked; btn.HorizontalOptions = LayoutOptions.Center; VLayout.Add(btn); 

Here the XAML

<ScrollView> <VerticalStackLayout x:Name="VLayout" Spacing="25" Padding="30,0" VerticalOptions="Center"> <Image Source="dotnet_bot.png" SemanticProperties.Description="Cute dot net bot waving hi to you!" HeightRequest="200" HorizontalOptions="Center" /> <Label Text="Hello, World!" SemanticProperties.HeadingLevel="Level1" FontSize="32" HorizontalOptions="Center" /> <Label Text="Welcome to .NET Multi-platform App UI" SemanticProperties.HeadingLevel="Level2" SemanticProperties.Description="Welcome to dot net Multi platform App U I" FontSize="18" HorizontalOptions="Center" /> <Entry x:Name="entry" Placeholder="Enter text" TextChanged="OnTextChanged" Completed="OnTextCompleted" /> <Button x:Name="KommenBtn" Text="Kommen" SemanticProperties.Hint="Counts the number of times you click" Clicked="OnCounterClicked" HorizontalOptions="Center" /> <Button x:Name="GehenBtn" Text="Gehen" SemanticProperties.Hint="Counts the number of times you click" Clicked="OnCounterClicked" HorizontalOptions="Center" /> </VerticalStackLayout> </ScrollView> 
0

2 Answers 2

5

To update UI after a change that affects the hierarchy (or positions) of controls:

 (VLayout as IView).InvalidateArrange(); 

NOTE: This is roughly equivalent to Xamarin.Forms layout.ForceLayout();

If not already in code running on UI MainThread, wrap it in Dispatch:

Dispatcher.Dispatch(() => (VLayout as IView).InvalidateArrange()); 
Sign up to request clarification or add additional context in comments.

1 Comment

Hello, thanks for your answer!! Unfortunately the bevahior still stays the same, UI isn't updated. Do you have an additional hint? thanks in advance & BW
4

Try to update UI on main thread , you can wrap your code into Application.Current.Dispatcher.Dispatch .

Sample code

Application.Current.Dispatcher.Dispatch(() => { var btn = new Button(); btn.Text = "Button " + count + " added"; btn.Clicked += OnCounterClicked; btn.HorizontalOptions = LayoutOptions.Center; VLayout.Add(btn); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.