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

C# WinForms:如何用SortedList填充ListBox展示猜词游戏最低猜次计分板

解决SortedList绑定ListBox的问题

方案一:手动遍历填充(最直接,符合要求)

循环遍历填充是完全可行的方案,代码简单直接,完全适配SortedList的使用要求:

  1. 先清空ListBox避免重复数据:
lsbScores.Items.Clear();
  1. 遍历SortedList的键值对,拼接成你需要的格式后逐个添加到ListBox:
foreach (KeyValuePair<string, int> entry in scores)
{
    lsbScores.Items.Add($"{entry.Key}: {entry.Value} 次");
}

这种方法不需要处理数据绑定的接口限制,逻辑直观,也方便调试。

方案二:转换为支持绑定的集合(保留排序特性)

如果想保留数据绑定的自动刷新特性,可以把SortedList的内容转换为实现IList接口的集合,同时自定义显示格式:

快速转换实现

直接将SortedList转成List<KeyValuePair<string, int>>,通过Format事件自定义显示文本:

var bindingCollection = new List<KeyValuePair<string, int>>(scores);
lsbScores.DataSource = bindingCollection;
// 绑定Format事件修改显示内容
lsbScores.Format += (sender, e) =>
{
    var kv = (KeyValuePair<string, int>)e.Value;
    e.Value = $"{kv.Key}: {kv.Value} 次";
};

规范实体类实现

创建实体类并重写ToString方法,让ListBox自动显示目标格式:

// 定义存储计分数据的实体类
public class ScoreItem
{
    public string Word { get; set; }
    public int MinGuessCount { get; set; }

    // 重写ToString,ListBox会自动调用此方法生成显示文本
    public override string ToString()
    {
        return $"{Word}: {MinGuessCount} 次";
    }
}

// 将SortedList转换为实体列表并绑定
var scoreItems = scores.Cast<KeyValuePair<string, int>>()
                       .Select(kv => new ScoreItem 
                       { 
                           Word = kv.Key, 
                           MinGuessCount = kv.Value 
                       })
                       .ToList();
lsbScores.DataSource = scoreItems;

报错原因说明

你遇到的ArgumentException是因为SortedList(无论泛型还是非泛型版本)未实现IList或IListSource接口,而WinForms的复杂数据绑定要求数据源必须实现这两个接口之一,因此直接赋值lsbScores.DataSource = scores会触发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:46:09