问题
I need to access the OnOff property in a Switch within the ListView.GroupHeaderTemplate this property is in the collection used by ListView.ItemTemplate, I have tried in many ways without success, has anyone ever had this problem?
>
<ListView
ItemsSource="{Binding ItemsGrouped}"
GroupShortNameBinding="{Binding Key}"
IsGroupingEnabled="true"
GroupDisplayBinding="{Binding Key}"
x:Name="ListViewAllDevices">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell.View>
<StackLayout>
<Label Text="{Binding Title}"/>
<Label Text="{Binding Description}"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Label Text="{Binding Key}" />
<Switch IsToggled="{Binding OnOff, Source={x:Reference Name=ListViewAllDevices}}"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
回答1:
I think you may to change the viewModel .Each groupHeaderTemplate can bind one value. My code as below:
Model
public class Person
{
public string FullName
{
get;
set;
}
public string Address
{
get;
set;
}
}
public class Group : ObservableCollection<Person>
{
public Group(bool key)
{
Key = key;
}
public bool Key
{
get;
private set;
}
}
ItemSource
listView.ItemsSource = new[] {
new Group (true) {
new Person { FullName = "Ass" ,Address = "cole house" }
},
new Group (false) {
new Person { FullName = "Caprice Nave" }
},
new Group (false) {
new Person { FullName = "James Smith", Address = "404 Nowhere Street"},
new Person { FullName = "John Doe", Address = "404 Nowhere Ave" }
}
};
XMAL
<ListView x:Name="listView" IsGroupingEnabled="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Label Text="{Binding FullName}"/>
<Label Text="{Binding Address}"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Switch IsToggled="{Binding Key}"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
</ListView>
PS: Once you setListView.GroupHeaderTemplate ,ListView.GroupDisplayBinding will set to null automatically, so you don't need to set ListView.GroupDisplayBinding , but don't forget IsGroupingEnabled="true"
来源:https://stackoverflow.com/questions/45357041/xamarin-forms-how-to-access-the-collection-used-in-listview-itemtemplate-within