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

从控制台程序迁移后,WPF ListBox无法显示MySQL游戏数据

解决WPF ListBox无法加载MySQL数据的问题

问题根源

你当前的代码存在两个核心问题:

  1. 错误地将集合转换为字符串赋值给ItemsSource:statistics.ReturnGames().ToString()返回的是集合的类型名称(比如System.Collections.Generic.List1[VideoGame]`),而非实际的游戏数据集合,导致ListBox无法识别数据。
  2. 未处理VideoGame对象的显示逻辑:ListBox默认会调用对象的ToString()方法,若未重写该方法,只会显示对象的类型名,而非游戏信息。

修复步骤

1. 修正ItemsSource赋值

移除.ToString(),直接将集合赋值给ItemsSource:

public MainWindow()
{
    InitializeComponent();
    // 去掉ToString(),直接返回集合
    gameList.ItemsSource = statistics.ReturnGames();
}

2. 确保ReturnGames()方法正确返回数据集合

在Statistics类中实现ReturnGames(),返回私有字段games:

// 在Statistics类中添加该方法
public List<VideoGame> ReturnGames()
{
    return games;
}

3. 让ListBox正确显示游戏信息(二选一)

方法一:重写VideoGame类的ToString()

在VideoGame类中重写方法,自定义显示文本:

public class VideoGame
{
    // 确保属性为public,方便后续绑定访问
    public int Id { get; set; }
    public string Title { get; set; }
    public string Platform { get; set; }
    public int ReleaseYear { get; set; }

    public VideoGame(int id, string title, string platform, int releaseYear)
    {
        Id = id;
        Title = title;
        Platform = platform;
        ReleaseYear = releaseYear;
    }

    // 重写ToString()定义显示内容
    public override string ToString()
    {
        return $"{Title} ({Platform}) - 发行年份: {ReleaseYear}";
    }
}
方法二:在XAML中自定义ItemTemplate

通过DataTemplate定制每个列表项的显示布局,这种方式更灵活:

<ListBox x:Name="gameList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="5" Orientation="Vertical">
                <TextBlock Text="{Binding Title}" FontSize="14" FontWeight="Bold"/>
                <TextBlock Text="平台: {Binding Platform}" FontSize="12" Foreground="Gray"/>
                <TextBlock Text="发行年份: {Binding ReleaseYear}" FontSize="12" Foreground="Gray"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

注意:此方法要求VideoGame类的属性为公共可访问(即public修饰符),否则数据绑定无法读取属性值。


优化建议(可选)

  • 使用ObservableCollection<VideoGame>替代List<VideoGame>:如果后续需要动态更新游戏列表(比如新增/删除游戏),ObservableCollection会自动通知UI刷新,无需手动更新ItemsSource。
  • 优化数据库连接资源管理:使用using语句自动释放数据库连接、命令和读取器资源,避免内存泄漏:
public void Initialize()
{
    string connStr = "server=localhost;user=root;database=gamesdb;port=3306;password=";
    // 使用using自动释放连接
    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        try
        {
            conn.Open();
            string sql = "SELECT id, title, platform, release_year FROM videogames";
            // 使用using自动释放命令
            using (MySqlCommand cmd = new MySqlCommand(sql, conn))
            {
                // 使用using自动释放读取器
                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {
                    games = new List<VideoGame>();
                    while (rdr.Read())
                    {
                        var game = new VideoGame(rdr.GetInt32(0), rdr.GetString(1), rdr.GetString(2), rdr.GetInt32(3));
                        games.Add(game);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Environment.Exit(1);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:53:09