我正在使用xamarin.forms开发企业应用程序。已经过去几天,ListView的内存泄漏问题对我来说成了一场噩梦。为简单起见,我将尝试用示例代码进行解释。
XAML页码 - 包含ListView和两个按钮的页面(添加和删除)
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ListViewTest"
x:Class="ListViewTest.MainPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<ListView Grid.Row="0" BackgroundColor="White" x:Name ="ItemsListView">
<ListView.ItemTemplate>
<DataTemplate >
<TextCell TextColor="Black" Text="{Binding ItemText}"
DetailColor="Black" Detail="{Binding ItemDetail}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Grid.Row="1" Text="Add" Clicked="AddItemClicked"/>
<Button Grid.Row="2" Text="Remove" Clicked="RemoveItemClicked"/>
</Grid>
</ContentPage>
C#代码背后 - 只需在集合中添加和删除对象。
public partial class MainPage : ContentPage
{
ObservableCollection<SampleData> itemsListCollection;
public MainPage()
{
InitializeComponent();
itemsListCollection = new ObservableCollection<SampleData>();
ItemsListView.ItemsSource = itemsListCollection;
}
void AddItemClicked(object sender, EventArgs e)
{
SampleData data = new SampleData();
data.ItemText = "An Item";
data.ItemDetail = "Item - " + (itemsListCollection.Count + 1).ToString();
itemsListCollection.Add(data);
}
void RemoveItemClicked(object sender, EventArgs e)
{
SampleData item = (SampleData)ItemsListView.SelectedItem;
if (item != null)
{
itemsListCollection.Remove(item);
}
}
}
数据类 - 只有两个属性
class SampleData
{
public event PropertyChangedEventHandler PropertyChanged;
private string itemText;
public string ItemText
{
get
{
return itemText;
}
set
{
itemText = value;
NotifyPropertyChanged("ItemText");
}
}
private string itemDetail;
public string ItemDetail
{
get
{
return itemDetail;
}
set
{
itemDetail = value;
NotifyPropertyChanged("ItemDetail");
}
}
private void NotifyPropertyChanged(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}
添加按钮 - 将项目添加到ListView
删除按钮 - 从ListView中删除项目
问题 -
Image - Memory Snapshot of original application
Image - Detailed Memory Snapshot of sample application