You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF应用无列表项时点击上下移动按钮报ArgumentOutOfRangeException异常

异常原因分析
  • 当列表框未插入任何条目时,listBox.SelectedIndex 的默认返回值为 -1,你的上下移动按钮点击逻辑中没有对该值做合法性校验,直接用-1做运算后得到的索引属于非法值,传入Insert方法就会触发参数越界异常
  • 即使列表内有条目,只要用户未选中任何内容,SelectedIndex同样会返回-1,也会触发相同报错
  • 额外隐藏问题:Verschieben方法中直接取listBox.SelectedItem,无选中项时该值为null,后续的移除、插入操作也会触发异常
解决方案

核心修复:增加前置合法性校验

分别修改两个移动按钮的点击事件,只有列表有内容且用户选中了条目时才执行移动逻辑:

private void btnNachOben_Click(object sender, RoutedEventArgs e)
{
    // 前置校验不通过直接终止执行
    if (listBox.Items.Count == 0 || listBox.SelectedIndex < 0)
        return;

    int index = listBox.SelectedIndex;
    if (index == 0)
        index = listBox.Items.Count - 1;
    else
        index--;
    Verschieben(index);
    statusLabel.Content = "Eintrag nach oben verschoben";
}

private void btnNachUnten_Click(object sender, RoutedEventArgs e)
{
    // 前置校验不通过直接终止执行
    if (listBox.Items.Count == 0 || listBox.SelectedIndex < 0)
        return;

    int index = listBox.SelectedIndex;
    if (index == listBox.Items.Count - 1)
        index = 0;
    else
        index++;
    Verschieben(index);
    statusLabel.Content = "Eintrag nach unten verschoben";
}

可选优化:给Verschieben方法增加兜底校验

避免其他位置调用该方法时也传入非法参数:

private void Verschieben(int index)
{
    // 兜底校验,参数非法直接返回
    if (index < 0 || index >= listBox.Items.Count || listBox.SelectedItem == null)
        return;

    Object item = listBox.SelectedItem;
    listBox.Items.Remove(item);
    listBox.Items.Insert(index,item);
    listBox.SelectedIndex = index;
}

交互体验优化

可以默认将两个移动按钮的IsEnabled属性设为False,在列表选中状态变更、条目增删时同步判断:只要列表为空或无选中项就禁用按钮,从交互层面避免用户误触发无效操作。

内容的提问来源于stack exchange,提问作者Saion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:54:03