简体   繁体   English

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

[英]How to replace item in a listbox?

I have a ListBox which contains a ContentMenu like follows: 我有一个包含ContentMenuListBox ,如下所示:

<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>

When I want to Delete the item in the 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);
     }

}

Now the problem is I also want to replace the SelectedItem in the listbox, so I assuming that I also should popup a ContextMenu and binding the ItemsSource to it? 现在的问题是我也想替换列表框中的SelectedItem ,所以我假设我还应该弹出一个ContextMenu并将ItemsSource绑定到它? How I suppose to do this? 我应该怎么做? Thanks in advance! 提前致谢!

You should be able to just delete the old entry the same way you did it in the delete method. 您应该能够像在delete方法中一样删除旧条目。 Then just use Items.InsertAt(Int32, Object) to insert an item into that same index. 然后只需使用Items.InsertAt(Int32, Object)将一个项目插入相同的索引即可。

For example, 例如,

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

If you want more details look at ListBox.Items.InsertAt() 如果您想了解更多详细信息,请查看ListBox.Items.InsertAt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM