,我不會建議使用可擴展的ListView,因爲它可能會導致性能問題時,有更多數據。
但是,如果你想實現它遵循以下步驟:
你的模型應該像列表列表內
public class Model1
{ public string Name { get; set; } public List<Model2> Model2Name { get; set; }
} public class Model2 { public string Name1 { get; set; } }
在此處輸入代碼
然後你的XAML應該像
<ListView
HasUnevenRows="True"
ItemSelected="ItemSelected"
ItemsSource="{Binding DataList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="9*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Text="{Binding Name}" YAlign="Center"/>
<ListView Grid.Row="1"
IsVisible="{Binding ListVisibility}"
SeparatorVisibility="None"
ItemSelected="ProductSelected"
HeightRequest="220"
BackgroundColor="#f2f2f2"
HorizontalOptions="FillAndExpand"
ItemsSource="{Binding Model.Products}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Name}"
YAlign="Center" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
現在你必須包裝你的模型。對於你必須寫一個包裝類如下:
public class WrapperModel<T> : INotifyPropertyChanged
{
public T Model { get; set; }
public event PropertyChangedEventHandler PropertyChanged = delegate { };
bool listVisibility = false;
public bool ListVisibility
{
get
{
return listVisibility;
}
set
{
if (listVisibility != value)
{
listVisibility = value;
PropertyChanged(this, new PropertyChangedEventArgs("ListVisibility"));
}
}
}
}
現在,在視圖模型,你必須聲明你的列表屬性如下:
private List<WrapperModel<ProductCategoryModel>> dataList;
public List<WrapperModel<ProductCategoryModel>> DataList
{
get { return dataList; }
set
{
dataList = value;
OnPropertyChanged("DataList");
}
}
現在初始化列表如下:
foreach (var item in List)
{
DataList.Add(new WrapperModel<ModelName>
{ Model = item, ListVisibility = false});
}
現在列表將處於摺疊狀態。要獲得點擊每個項目內部列表,你必須設置ItemSelected如下:
private void ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null) return;
var tappedItem = (WrapperModel<ModelName>)e.SelectedItem;
tappedItem.ListVisibility = !tappedItem.ListVisibility;
((ListView)sender).SelectedItem = null;
}
如果您有疑問,請讓我知道