【问题标题】:ListBox won't remove the first item in c#ListBox 不会删除 C# 中的第一项
【发布时间】:2016-10-22 23:54:18
【问题描述】:
private void button_Click(object sender, RoutedEventArgs e) //ADD
{
    listBox.Items.Add("some");
    listBox.Items.Add("text");         

}


private void button1_Click(object sender, RoutedEventArgs e) //DELETE
{

    if (!(listBox.SelectedIndex == -1))
       listBox.Items.Remove(listBox.SelectedItem);
    else
        System.Windows.MessageBox.Show("You have not selected an item");

}

ListBox 有时不会删除第一项。原因是在我删除一个项目后,前一个项目上会出现白色边框。我不知道为什么会出现这个边框。请参阅图片以了解我的意思。当出现白色边框并且我尝试删除第一个项目时,它表示我没有选择一个项目。 如果我保存 3 次相同的项目并删除第二次,则会出现错误。

试试看。例如一些,一些,一些

【问题讨论】:

  • 无法重现您的意思,正确的行为,请参见此处:imgur.com/a/0Brvt
  • @DoubleVoid 试试 listBox.Items.Add("some"),listBox.Items.Add("some"),listBox.Items.Add("some");并首先删除第二个
  • 它现在的行为是这样的:imgur.com/yNyPJFU ... 我觉得还可以
  • @DoubleVoid 添加 3 次相同的项目而不是一次。每个按钮单击一项。
  • 只需将其绑定到 ObservableCollection 并在集合上添加/删除。不要浪费时间玩这样的游戏。

标签: c# wpf listbox listboxitem


【解决方案1】:

尝试将项目从其位置而不是项目本身移除。我发现这样做不再选择另一个项目,因为焦点已从列表框中完全移除。

private void button1_Click(object sender, RoutedEventArgs e)
{
   if (listBox.SelectedIndex != -1)
      listBox.Items.RemoveAt(listBox.SelectedIndex);

   else
      System.Windows.MessageBox.Show("You have not selected an item");

}

【讨论】:

    【解决方案2】:

    尝试像这样选择下一个项目:

        private void button2_Click(object sender, EventArgs e)
        {
            if (!(listBox1.SelectedIndex == -1))
            {
                int index = listBox1.SelectedIndex;
                listBox1.Items.Remove(listBox1.SelectedItem);
    
                if (index > 0)
                    listBox1.SetSelected(index - 1,true);
                else if(listBox1.Items.Count > 0)
                    listBox1.SetSelected(0, true);
    
    
            }
            else
                MessageBox.Show("You have not selected an item");
        }
    

    行为:

    【讨论】:

    • 这不会删除列表框中的正确项目
    【解决方案3】:

    button1_click 事件中的代码应该是这样的

    var index = listBox.SelectedIndex;
    
    if (index != -1)
    {
        // remove item
        listBox.Items.RemoveAt(index);
    
        // select a new item
        if (listBox.Items.Count > index)
            listBox.SelectedIndex = index;
        else
            listBox.SelectedIndex = index - 1;
     }
     else
        System.Windows.MessageBox.Show("You have not selected an item");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      相关资源
      最近更新 更多