【问题标题】:ObservableCollection ListBox Item Remove Not WorkingObservableCollection ListBox 项目删除不起作用
【发布时间】: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


【解决方案1】:

除了 Joan 说的,你也可以像这样在 Xaml 中这样做:

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

</ListBox>

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

不要气馁。刚开始有点学习,但完全值得。在我开始使用 Laurent Bugnions 的 MvvmLight 包对 MVVM 进行所有操作之前,我在显示列表方面也遇到了一些问题。

【讨论】:

    【解决方案2】:

    试试这个:

    private void DeletePerson_Click(object sender, RoutedEventArgs e)
        {   
           System.Collections.IList pathRemove;
           pathRemove = lstPerson.SelectedItems;
    
           if(pathRemove.Count != 0)
              {
                   for (int i = pathRemove.Count - 1; i >= 0; i--)
                        {
                            lstPerson.Remove((Person)pathRemove[i]);//multiple deletes
                        } 
             }
    
    
        } 
    

    【讨论】:

    • 感谢您的回答。我已经对其进行了调试,listBox.SelectedIndex 存在问题,值为-1。所以 ContextMenu 不在正确的位置,因为我没有得到选定的索引
    【解决方案3】:

    在表单初始化的时候尝试添加这个:

    lstPersons.ItemsSource = personList ;
    

    How to: Create and Bind to an ObservableCollection

    问题似乎是由于所选项目引起的

    关键是设置 PreviewMouseRightButtonDown 事件 正确的地方。您会注意到,即使没有 ContextMenu 权限 单击 ListViewItem 将选择该项目,因此我们需要 在每个项目上设置事件,而不是在 ListView 上。

    <ListView>
        <ListView.ItemContainerStyle>
            <Style TargetType="{x:Type ListViewItem}">
                <EventSetter Event="PreviewMouseRightButtonDown"
                             Handler="OnListViewItemPreviewMouseRightButtonDown" />
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Menu Item">Item 1</MenuItem>
                <MenuItem Header="Menu Item">Item 2</MenuItem>
            </ContextMenu>
        </ListView.ContextMenu>
        <ListViewItem>Item</ListViewItem>
        <ListViewItem>Item</ListViewItem>
        <ListViewItem>Item</ListViewItem>
        <ListViewItem>Item</ListViewItem>
        <ListViewItem>Item</ListViewItem>
        <ListViewItem>Item</ListViewItem>
    </ListView>
    

    .

    private void OnListViewItemPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        Trace.WriteLine("Preview MouseRightButtonDown");
    
        e.Handled = true;
    }
    

    wpf listview right-click problem

    【讨论】:

    • 感谢您的回答。我试过了,但我认为删除项目的 ContextMenu Delete 事件代码不起作用。
    • 您确定lstPerson.SelectedIndex 的值正确吗?
    • 问题是 SelectedIndex 的值可能是上下文菜单不在正确的位置,或者我有错误事件
    • 谢谢哥们,但我终于解决了问题!
    • 太棒了! :) 祝你有美好的一天!
    【解决方案4】:

    为什么不对所有人使用绑定。

    将项目源绑定为 ObservableCollection blabla

    将 Selecteditem 绑定为 XXXX

    为你的按钮使用命令,当你想删除一个项目时:

    blabla.remove(SelectedItem);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多