LongListSelector中的超链接按钮

本文关键字:按钮 超链接 LongListSelector | 更新日期: 2023-09-27 18:04:35

在我的项目模板在longlistselector我有一个超链接按钮。
当我点击按钮时,该项目应该被删除。
问题是,如果没有选择的项目,我需要单击两次按钮,因为在LonglistSelector中首次单击SelectedItem后为空。
如何修复它,点击按钮会自动设置列表上的选择按钮的父?

LongListSelector中的超链接按钮

您可以通过两种不同的方式做到这一点(忽略MVVM模式)。您可以在HyperLinkButton Click事件处理程序中删除该项,您可以设置LongListSelectorSelectedItem,因此您可以在之后删除该项。

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);
}