How to refresh LongListSelector after delete an it

2019-06-06 14:50发布

I have a LongListSelector like that

<phone:LongListSelector Name="ListRecentFiles"
                                        LayoutMode="Grid"
                                        ItemsSource="{Binding}"
                                        GridCellSize="140,140"
                                        SelectionChanged="ListRecentFiles_SelectionChanged">

                        <phone:LongListSelector.ItemTemplate>
                            <DataTemplate>
                                <Grid Background="Red" Margin="0,0,5,5">
                                    <TextBlock Text="{Binding NoteTitle}" Style="{Binding PhoneTextNormalStyle}" />
                                    <toolkit:ContextMenuService.ContextMenu>
                                        <toolkit:ContextMenu x:Name="ContextMenu">
                                            <toolkit:MenuItem x:Name="Delete" Header="Delete" Click="DeleteNote_Click" />
                                        </toolkit:ContextMenu>
                                    </toolkit:ContextMenuService.ContextMenu>
                                </Grid>
                            </DataTemplate>
                        </phone:LongListSelector.ItemTemplate>
                    </phone:LongListSelector>

this is DataContext: public static ObservableCollection<Note> NoteItems;

And i try to delete an item from LongListSelector

private void DeleteNote_Click(object sender, RoutedEventArgs e)
{
    Note selectedNote = (sender as MenuItem).DataContext as Note;
    ListRecentFiles.ItemsSource.Remove(item);
    NoteItems.Remove(selectedNote);
}

It's not work except i navigate to a other XAML page and return

I have visited this page but can't fix link

1条回答
狗以群分
2楼-- · 2019-06-06 15:30

Without seeing more of the code, it's hard to be sure what's going wrong. But if you are setting

ListRecentFiles.DataContext = NoteItems;

that is incorrect. You want to set

ListRecentFiles.ItemsSource = NoteItems;

The XAML declaration:

ItemSource="{Binding}"

Could do that (depending on the rest of the code). Once .ItemsSource is set correctly, then the line:

NoteItems.Remove(selectedNote); 

Should succeed in removing the visual item from the LongListSelector. In any case, you should not do the line:

ListRecentFiles.ItemsSource.Remove(item);

That would do the wrong thing when the list gets so big that it doesn't all fit in memory at once.

查看更多
登录 后发表回答