【发布时间】:2013-08-30 23:22:17
【问题描述】:
我有一个带绑定的 ListBox,当我添加项目时它工作得很好,但如果我尝试使用 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); };
}
【问题讨论】:
-
在将
personList分配给ItemsSource之前添加项目是否有效?如果不是,则存在绑定问题。另外,这是一个错字吗?应该是ItemsSource而不是ItemSource。 -
以什么方式不起作用?异常,或者没有异常并且项目仍在列表中?
-
感谢大家的回答。我已经对其进行了调试,listBox.SelectedIndex 存在问题,值为-1。所以 ContextMenu 不在正确的位置,因为我没有得到选定的索引
标签: c# silverlight xaml windows-phone-8