我正在爲UWP使用Xamarin.Forms。如何在Xamarin.Forms上更改頁面時禁用ListView重新加載項目?
我有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頁之間切換。
該頁面已完成加載。這是該頁面的例子:
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項目,我只創建一次頁面。
如果你使用MasterDetailPage爲什麼你想改變整個App.MainPage,如果有人點擊一個ListViewItem?使用MasterDetailPage.Detail = new NavigationPage(new Foo());並在項目點擊只是做一個Navigation.PushAsync(新的BarWhichDependsOnItem()); –
@ Nitro.de嗨,朋友。看起來你不明白。我從來沒有說過我只更改整個'App.MainPage',如果你看得清楚,你會發現還有'MasterDetails.Detail =' – qakmak
如果你想隱藏MasterDetailPage-菜單按鈕被輕敲後使用導航.PushModalAsync,所以MasterDetail被隱藏,直到你再次popModal –