In my item template in longlistselector I have a hyperlink button.
When I'm clicking on button, that item should be deleted.
The problem is that if there is no selected item, I need to click twice on button, because after first click SelectedItem in LonglistSelector is null.
How to fix it, that click on button will automatically set selection on list to button's parent?
You can do this in two different ways (ignoring MVVM pattern). You can delete the item in the Click
eventhandler of the HyperLinkButton
or you can set the SelectedItem
of the LongListSelector
, so you can delete it right after.
public ObservableCollection<object> List { get; set; }
public MainPage()
{
InitializeComponent();
List = new ObservableCollection<object>() { "aaaa", "bbb", "cccc", "dddd", "eeee"};
LongList.ItemsSource = List;
}
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
var hyperLinkButton = sender as HyperlinkButton;
var boundItemDataContext = hyperLinkButton.DataContext;
List.Remove(boundItemDataContext); // #1 Delete it directly from the list that automatically gets updated because it's an ObservableCollection.
LongList.SelectedItem = boundItemDataContext; // #2 Set the SelectedItem property to the current DataContext, so you can delete it in the SelectionChanged eventhandler.
}
private void LongList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var longListSelector = sender as LongListSelector;
List.Remove(longListSelector.SelectedItem);
}