我只是在玩。net MAUI。我想从Rest服务中检索信息,并基于结果,我想以编程方式将Buttons添加到VerticalStackLayout。当我调试解决方案时,按钮被添加到垂直堆栈布局,但UI没有更新。
下面是代码片段var btn = new Button();
btn.Text = "Button " + count + " added";
btn.Clicked += OnCounterClicked;
btn.HorizontalOptions = LayoutOptions.Center;
VLayout.Add(btn);
这里是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>
提前感谢你的提示&的帮助!BW
在控件的层次结构(或位置)发生变化后更新UI:
(VLayout as IView).InvalidateArrange();
注意:这大致相当于Xamarin。表单layout.ForceLayout();
如果不在UI主线程上运行的代码中,将其封装在Dispatch中:
Dispatcher.Dispatch(() =>
(VLayout as IView).InvalidateArrange());
尝试在主线程上更新UI,您可以将代码包装到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);
});
Application.Current.Dispatcher.Dispatch(() =>
{
var btn = new Button();
btn.Text = "Button " + count + " added";
btn.Clicked += OnCounterClicked;
btn.HorizontalOptions = LayoutOptions.Center;
VLayout.Add(btn);
});