Windows Phone - removes items from ListPicker and refreshes data source in full mode

I have a ListPicker whose source is an observable collection. I added a context menu to this list so that the user can long press on any item to edit / delete it. I have two problems regarding deletion:

1- If I remove any item from the observable collection, this change is not reflected in full mode, I need to close the collector and reopen it, then I see that the item is removed.

2- if the item to be removed is the last item, removing it will throw an exception: System.InvalidOperationException: SelectedItem must always be set to a valid value

this is part of my xaml:

<toolkit:ListPicker Header="Shipping Addresses" Name="lst_ShippingAddresses" ExpansionMode="FullScreenOnly">
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding AddressCaption}" Margin="0,10" FontSize="26"/>
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu>
                        <toolkit:MenuItem Header="Edit" Click="EditShippingAddress"/>
                        <toolkit:MenuItem Header="Delete" Click="DeleteShippingAddress"/>
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>
            </StackPanel>
        </DataTemplate>
</toolkit:ListPicker>

      

and this is the delete function:

private void DeleteShippingAddress(object sender, RoutedEventArgs e)
{
    Dispatcher.BeginInvoke(() =>
    {
        MenuItem item = sender as MenuItem;
        ShippingAddress address = item.DataContext as ShippingAddress;

        if (lst_DeliveryAddresses.SelectedItem == address)
        {
            if (lst_DeliveryAddresses.Items.Count == 1) // last element in list
            {
                shippingAddresses.Clear();
            }
            else
            {
                if (lst_DeliveryAddresses.SelectedIndex == 0) // first element
                    lst_DeliveryAddresses.SelectedIndex = lst_DeliveryAddresses.SelectedIndex + 1;
                else
                    lst_DeliveryAddresses.SelectedIndex = lst_DeliveryAddresses.SelectedIndex - 1;
                shippingAddresses.Remove(address);

            }
        }
        else
        {
            shippingAddresses.Remove(address);
        }
    });
}

      

How do I update a data source in full mode? I tried lst_DeliveryAddresses.UpdateLayout()

but didn't use. And how can I clear the ListPicker data source without getting this exception?

Please help, thanks!

+3


source to share





All Articles