As the following approach seems not to work, I might miss a central concept of updating Xamarin.Forms ListView. Maybe you can help, how it should be done correctly.
I have got the following situation in a Xamarin.Forms Page: One ListView like that on a Page:
<ListView x:Name="listView" Margin="0" ItemSelected="OnListItemSelected" ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
...
</ListView.ItemTemplate>
</ListView>
This ListView's binding is connected to Items in the ViewModel that looks basically like the following:
private ObservableCollection<Item> items = new ObservableCollection<Item>();
public ObservableCollection<Item> Items
{
get
{
items.Clear();
if (SomeSingeltonSource != null)
{
IEnumerable<Item> current = SomeSingeltonSource.GetCurrentItems(viewModelState);
foreach (Item wf in current)
{
items.Add(wf);
}
}
return items;
}
}
And the method called on ItemSelected starts like the following:
void OnListItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem is Item selectedItem)
{
...
}
}
Now on the after the first binding, everything works fine. But if the Items change the List is still correctly updated, however if I select an Item on the list, the OnListItemSelected method is still called, however e.SelectedItem is always null.
Everything worked fine until Xamarin.Forms 3.0.0 Service Release 1 but since Service Release 2 it is not working anymore.
Do I miss an important concept of updating a ListView or is there something else that is implemened the wrong way?
Generally when I use Binding
for the ItemsSource
, I'll also be using Binding
for the SelectedItem
. That way you don't need to have any method/event hookup.
So in you example do this in your view:
<ListView x:Name="listView" Margin="0" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
...
</ListView.ItemTemplate>
</ListView>
And add an extra property in your binding context code like:
private Item _selectedItem;
public Item SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value; // TODO: Add extra code to trigger something because the user selected an item
OnNotifyPropertyChanged();
}
}
In the end it turned out that it has been a bug in Xamarin.Forms that has been solved in version 3.1.0.
If you are interested in the details, please have a look at the following issues:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.