以编程方式添加控件,UI 未更新

Pet*_* K. 12 maui

我只是在玩.Net MAUI。我想从 Rest 服务检索信息,并根据结果以编程方式将按钮添加到 VerticalStackLayout。当我调试解决方案时,按钮会添加到 VerticalStackLayout 但 UI 不会更新。

这是代码片段

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

这里是 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>
Run Code Online (Sandbox Code Playgroud)

Too*_*eve 5

要在影响控件层次结构(或位置)的更改后更新 UI:

    (VLayout as IView).InvalidateArrange();
Run Code Online (Sandbox Code Playgroud)

注意:这大致相当于 Xamarin.Formslayout.ForceLayout();

如果尚未在 UI MainThread 上运行的代码中,请将其包装在 Dispatch 中:

Dispatcher.Dispatch(() =>
    (VLayout as IView).InvalidateArrange());
Run Code Online (Sandbox Code Playgroud)