[英]How to disable ListView reload items when change page on Xamarin.Forms?
我正在为 UWP 使用 Xamarin.Forms。
我有 2 页,我需要一些时间切换它们:
// Change main page
App.Current.MainPage = otherPage; // this is not a new page, already exists
// Navigate
App.Current.MainPage.Navigation.PushAsync(otherPage); // this is not a new page, already exists
// Change detail page
MasterDetailsPage.Detail = otherPage; // this is not a new page, already exists
页,只需在 2 页之间切换。
otherPage
是已经完成加载的页面。 这是此页面的示例:
public partial class Page1 : ContentPage
{
public Page1 ()
{
InitializeComponent ();
ObservableCollection<StateModel> strList = new ObservableCollection<StateModel>();
for (int i = 1; i < 100; i++)
{
strList.Add(new StateModel() { Price = i, ProductName = "Product " + i });
}
btn.Clicked += (sender, args) =>
{
// change to another page which already finish load
App.Current.MainPage = StaticPage.Page2;
};
}
}
这是 XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.Page1">
<Grid>
<StackLayout>
<Label Margin="6,20,0,0" Text="scroll items and click go to other page and return you will find the listview reset: scroll on the top(I only change the App.Current.MainPage, not create new page)"/>
<Button x:Name="btn" Text="Go" />
<ListView x:Name="lvList" Margin="0,10,0,0" ItemsSource="{Binding }" IsRefreshing="False">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding ProductName}" HorizontalOptions="FillAndExpand" />
<Label Grid.Column="1" Text="{Binding Price}" Margin="10,0" />
<Label Text="" Grid.Column="2" HorizontalOptions="EndAndExpand" Margin="0,0,10,0">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding Price}" Value="90">
<Setter Property="Text" Value=">>>>>"/>
</DataTrigger >
</Label.Triggers>
</Label>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</Grid>
</ContentPage>
但它总是在更改页面时重新加载 ListView 项目,项目一个一个添加(就像某种动画一样)
就像每次 ListView 在切换页面时显示时一样,它会执行以下操作:
ListView.Clear();
ListView.Add();
ListView.Add();
ListView.Add();
// -- continue add 100 items --
这将使页面加载速度非常慢,对我来说是一个很大的性能问题。 它也会在我滚动之前丢失滚动位置,它会滚动到顶部(因为它清除并再次添加所有项目。),而且我不知道上次我选择了哪个项目,它会丢失。
反正有办法解决吗? 谢谢。
更新:
public static class StaticPage
{
public static Page1 Page1;
public static Page2 Page2;
public static void Init()
{
Page1 = new Page1();
Page2 = new Page2();
}
}
有些朋友需要这个,这就是我添加它的原因。 为什么我使用它,因为只是为了让您理解,我从不手动重新加载 ListView 项目,我只创建一次页面。
原来它是来自 Xamarin.Forms 的错误。
查看详情:
当导航到现有页面或返回到最后一页时,ScrollViewer 将重置滚动位置
已经1年多了,即使有人发了pull request来修复它,Xamarin团队也没有合并代码。 也许 Xamarin 团队几年前就已经知道 Windows Phone 会死。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.