我有一个带有绑定的 ListBox,当我添加 Items 时它工作得很好,但是如果我尝试使用 contextMenu 删除项目,它就不起作用。
这是我到目前为止尝试的ListBox Xaml 代码
<ListBox Name="lstPersons"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch" Margin="126,-228,2,-242">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu Name="PersonContext">
<toolkit:MenuItem Name="PersonDelete" Header="Delete" Click="DeletePerson_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="btnKellnerName"
Text="{Binding _PersonName}"
FontSize="35"
FontFamily="Portable User Interface"/>
<TextBlock Name="btnPosition"
Text="{Binding _PersonPosition}"
FontSize="22"/>
<TextBlock Name="lblUhrzeit"
Text="{Binding _CreationDate}"
FontSize="18"/>
<TextBlock Name="Space" Text=" "/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
和绑定类代码
public class Person
{
public string _PersonName { get; set; }
public string _PersonPosition { get; set; }
public string _CreationDate { get; set; }
}
当我添加这样的项目时
ObservableCollection<Person> personList = new ObservableCollection<Person>();
personList.Add(new Person {
_PersonName = "Tom",
_PersonPosition = "Bla",
_CreationDate = "33"
});
this.lstPerson.ItemSource = personList;
效果很好!现在我想像这样使用 ContextMenu 删除选定的项目
private void DeletePerson_Click(object sender, RoutedEventArgs e)
{
int indexPerson = lstPerson.SelectedIndex;
personList.RemoveAt(indexPerson);
}
但它不起作用。有人知道我做错了什么吗?谢谢
好的,伙计们,我现在有了解决方案问题是 SelectedIndex 的值现在我得到了正确的值。首先,我将 ContextMenu 放入 ListBoxItemTemplate/StackPanel
代码背后:
private void DeletePerson_Click(object sender, RoutedEventArgs e)
{
try {
var selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(((MenuItem) sender).DataContext) as ListBoxItem;
var selectedIndex = listBox.ItemContainerGenerator.IndexFromContainer(selectedListBoxItem);
_personList.RemoveAt(selectedIndex);
}
catch( Exception ex ) { MessageBox.Show(ex.Message); };
}