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

如何根据字符串定位ListBox目标条目并滚动至该位置高亮显示

实现ListBox间的条目匹配、滚动与高亮显示

以下以C# WinForms为例,实现你需要的功能:

核心逻辑

  • 监听listBoxSearch的选中变化事件,触发匹配操作
  • 提取选中条目的文本内容,在listBoxTxt中查找对应匹配项
  • 选中匹配条目并滚动至可见位置(ListBox默认选中条目即为高亮状态)

代码实现

  1. 为listBoxSearch绑定SelectedIndexChanged事件(可在设计器双击控件自动生成,或手动添加):
private void listBoxSearch_SelectedIndexChanged(object sender, EventArgs e)
{
    // 判空,避免无选中项时触发错误
    if (listBoxSearch.SelectedItem == null) return;
    
    // 提取搜索框选中的文本(若绑定自定义对象,需转成对应类型后读取属性)
    string targetText = listBoxSearch.SelectedItem.ToString();

    // 遍历目标ListBox查找匹配条目
    for (int i = 0; i < listBoxTxt.Items.Count; i++)
    {
        string currentItemText = listBoxTxt.Items[i].ToString();
        // 完全匹配规则,可改为Contains实现包含匹配,或添加StringComparison忽略大小写
        if (currentItemText.Equals(targetText, StringComparison.OrdinalIgnoreCase))
        {
            // 选中条目并滚动至可视区域
            listBoxTxt.SelectedIndex = i;
            listBoxTxt.EnsureVisible(i);
            break; // 找到第一个匹配项后停止遍历,如需全匹配可移除该语句
        }
    }
}

自定义对象场景适配

如果listBoxTxt绑定的是自定义类对象(而非纯字符串),需调整文本提取逻辑:

// 假设自定义类为ItemModel,包含Text属性
var targetItem = (ItemModel)listBoxSearch.SelectedItem;
string targetText = targetItem.Text;

// 遍历查找时同理转换
var currentItem = (ItemModel)listBoxTxt.Items[i];
string currentItemText = currentItem.Text;

简化查找的可选方案

可以用ListBox内置的查找方法简化逻辑:

int matchIndex = listBoxTxt.FindStringExact(targetText); // 完全匹配
// 若需前缀匹配,改用listBoxTxt.FindString(targetText);
if (matchIndex != ListBox.NoMatches)
{
    listBoxTxt.SelectedIndex = matchIndex;
    listBoxTxt.EnsureVisible(matchIndex);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:55:20