gpt4 book ai didi

c# - ObservableCollection ListBox 项目删除不工作

转载 作者:行者123 更新时间:2023-11-30 18:32:33 25 4
gpt4 key购买 nike

我有一个带绑定(bind)的列表框,当我添加项目时它工作得很好但是如果我尝试使用上下文菜单删除项目它不起作用。

这是我目前尝试的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>

绑定(bind)类代码

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

最佳答案

除了 Joan 所说的之外,您还可以像这样在 Xaml 中执行此操作:

<ListBox ItemsSource={Binding personList}
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch" Margin="126,-228,2,-242">
<toolkit:ContextMenuService.ContextMenu>

</ListBox>

您应该阅读如何使用绑定(bind)和 MVVM 模型。像这样的东西很方便。以下是一些链接: http://channel9.msdn.com/Events/MIX/MIX10/EX14 http://channel9.msdn.com/Events/MIX/MIX11/OPN03

不要气馁。一开始需要学习一些东西,但完全值得。在我开始使用 Laurent Bugnions 的 MvvmLight 包使用 MVVM 做所有事情之前,我在显示列表方面也遇到了一些问题。

关于c# - ObservableCollection ListBox 项目删除不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18533664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com