如何替换列表框中的项目?

时间:2017-10-24 03:07:28

标签: c# wpf listbox contextmenu

我有ListBox,其中包含ContentMenu,如下所示:

<ListBox x:Name="lb_Configuration" SelectionMode="Single" SelectionChanged="lb_Configuration_SelectionChanged" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}" >
     <ListBox.ContextMenu>
          <ContextMenu>
               <MenuItem Header="Delete" Click="MenuItemDelete_Click"/>
               <MenuItem Header="Replace" Click="MenuItemReplace_Click"/>
               <MenuItem Header="Insert" Click="MenuItemInsert_Click"/>
          </ContextMenu>
     </ListBox.ContextMenu>                                                    
</ListBox>

当我想Delete中的ListBox项目时,private void MenuItemDelete_Click(object sender, RoutedEventArgs e) { Product itemToDelete = lb_Configuration.SelectedItem as Product; if (lb_Configuration.SelectedIndex < 0) return; else { lb_Configuration.Items.RemoveAt(lb_Configuration.SelectedIndex); } }

SelectedItem

现在问题是我还想替换列表框中的ContextMenu,所以我假设我还应该弹出ItemsSource并将SELECT sc FROM ShoppingCart sc JOIN sc.endUser as endUser WHERE endUser.name EQ someName and endUser.addressDetails.zip EQ 1234绑定到它?我怎么想这样做?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您应该能够像删除方法一样删除旧条目。然后只需使用Items.InsertAt(Int32, Object)将项目插入到同一索引中。

例如,

private void MenuItemReplace_Click(object sender, RoutedEventArgs e)
{
     Product replacementProduct = new Product();
     // Grab the old index
     int index = lb_Configuration.SelectedIndex;
     // Do any product setup configuration here 

     if (index < 0) return;
     else
     {
         // Remove, insert, and refresh the ListBox
         lb_Configuration.Items.RemoveAt(index);
         lb_Configuration.Items.InsertAt(index, replacementProduct); 
         lb_Configuration.RefreshItems();
     }
}

如果您想了解更多详细信息,请查看ListBox.Items.InsertAt()