Reputation: 153
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>
Upvotes: 12
Views: 7635
Reputation: 1
Application.Current.Dispatcher.Dispatch(() =>
{
(verticalstacklayout as IView).InvalidateArrange();
DetailItemTextBox deta = new DetailItemTextBox();
deta.Text = "World";
deta.TextFontHeight = 30;
verticalstacklayout.Children.Add(deta as IView);});
Tried to update UI on main thread, but not adding to layout.
Upvotes: 0
Reputation: 21321
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());
Upvotes: 5
Reputation: 14475
Try to update UI on main thread , you can wrap your code into Application.Current.Dispatcher.Dispatch
.
Application.Current.Dispatcher.Dispatch(() =>
{
var btn = new Button();
btn.Text = "Button " + count + " added";
btn.Clicked += OnCounterClicked;
btn.HorizontalOptions = LayoutOptions.Center;
VLayout.Add(btn);
});
Upvotes: 4