[英]How to load element asynchronously
我希望每個模板都可以單獨加載到我的堆棧面板中,而不必等到它們都准備就緒,有沒有辦法讓它一個接一個地加載而程序沒有凍結,而其他模板仍然加載?
在這里,我將listview收費到stackpanel
public MainPage()
{
this.InitializeComponent();
setdata();
}
public async void setdata()
{
for (int i = 0; i < 30; i++)
{
DataTemplate template = this.Resources["listT"] as DataTemplate;
var element = template.LoadContent() as UIElement;
ListView list = element as ListView;
for (int j = 0; j < 20; j++)
{
listS.Add("t: " + j);
}
list.DataContext = listS;
root.Children.Add(list);
}
}
和
<Page.Resources>
<ResourceDictionary>
<ItemsPanelTemplate x:Key="HorizontalTemplate">
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
<DataTemplate x:Key="HorizontalBoxeSectionTemplate">
<Grid Background="White">
<Image Source="/Assets/image.jpg" Stretch="UniformToFill"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="listT">
<ListView Grid.Row="1"
IsItemClickEnabled="True"
ScrollViewer.HorizontalScrollMode="Enabled"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.IsHorizontalRailEnabled="True"
ItemsPanel="{StaticResource HorizontalTemplate}"
ItemsSource="{Binding }"
ItemTemplate="{StaticResource HorizontalBoxeSectionTemplate}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</DataTemplate>
</ResourceDictionary>
</Page.Resources>
<StackPanel Name="root">
</StackPanel>
您的代碼中存在三個問題。
首先,您需要了解異步編程。 這並不意味着您向方法添加async
關鍵字,然后它將成為異步方法。 請參閱使用async進行異步編程並在c#中等待學習異步編程,並在UWP中查看異步編程以獲取更多詳細信息。
第二,使用StackPanel
作為ListView的ItemsPanelTemplate。 這涉及與UI虛擬化相關的內容。 總之,使用StackPanel
會降低ListView的性能。 您可以使用ItemsStackPanel
。 有關更多信息,請參閱ListView和GridView UI優化 。
第三,你最好不要在頁面的構造函數中調用異步方法。 相反,您可以在頁面的Loaded事件處理程序中調用它。
對於你上面的代碼片段,我做了一些更改,並防止它阻止UI線程。 為了更清楚地看到,我添加了這個行代碼await Task.Delay(1000);
。 然后您將清楚地看到ListView逐行添加到UI上,但頁面仍然是響應式的。
<ItemsPanelTemplate x:Key="HorizontalTemplate">
<ItemsStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await setdata();
}
public List<string> listS { get; set; } = new List<string>();
public async Task setdata()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
for (int i = 0; i < 30; i++)
{
DataTemplate template = this.Resources["listT"] as DataTemplate;
var element = template.LoadContent() as UIElement;
ListView list = element as ListView;
for (int j = 0; j < 20; j++)
{
listS.Add("t: " + j);
}
list.DataContext = listS;
root.Children.Add(list);
await Task.Delay(1000);
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.