【问题标题】:Winforms c# listbox not displaying contents of listWinforms c#列表框不显示列表内容
【发布时间】:2023-03-22 20:19:02
【问题描述】:

我有一个正在尝试使用 MVC 编程的 winforms 应用程序

在我的表单的designer.cs中:

    this.listBox_regApps = new System.Windows.Forms.ListBox();
    this.listBox_regApps.Anchor = System.Windows.Forms.AnchorStyles.Top;
    this.listBox_regApps.FormattingEnabled = true;
    this.listBox_regApps.Location = new System.Drawing.Point(62, 115);
    this.listBox_regApps.Name = "listBox_regApps";
    this.listBox_regApps.Size = new System.Drawing.Size(351, 134);
    this.listBox_regApps.TabIndex = 1;

然后稍后在普通的 cs 文件中,我尝试将列表框数据设置为列表(应用程序)。当我调试列表应用程序时确实有数据,但它从未出现在表单中。不知道为什么。我尝试添加 .update 和 .refresh ,但它们都不起作用。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AppCompatDemo1
{
    interface IAppView
    {
        void AddListener(IController controller);
    };



    public partial class AppCompatApp : Form, IAppView
    {
        IController controller;
        public AppCompatApp()
        {

            InitializeComponent();
        }

        public void AddListener(IController controller)
        {
            this.controller = controller;
        }

        //Trying to set my listbox to display this list
        public void SetApps(List<string> apps)
        {
            listBox_regApps.DataSource = apps;
        }




    }

    public interface IController
    {
        void OnTestClick(string currentApp);
    }

    class AppController : IController
    {
        AppCompatApp view;
        IAppModel model;

        public AppController(IAppModel model, AppCompatApp view)
        {
            this.model = model;
            this.view = view;
            this.view.AddListener(this);
            view.SetApps(model.getApps());
        }

    }

    interface IAppModel
    {
        List<string> getApps();
    }

    class AppModel : IAppModel
    {
        List<string> apps;
        public AppModel()
        {
            apps = new List<string>();
            apps.Add("app1");
            apps.Add("app2");
            apps.Add("app3");
        }

        public List<string> getApps()
        {
            return apps;
        }

    }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    类似的东西。

    foreach (string app in apps)
    {
        listBox_regApps.Items.Add(app);
    }      
    

    【讨论】:

    • 记得清除旧项目列表框。 "listBox_regApps.Items.Clear();"
    • 其实我也试过了,还是空白。我在错误的部分做错了吗?
    • 您是否为您的“Setapps: 方法添加了按钮事件?您在哪里调用它?如何触发它?
    • 欢迎来到 Stack Overflow!请添加一些解释,说明此代码如何/为什么对 OP 有帮助。这将有助于为未来的观众提供一个可以学习的答案。请参阅How to Answer 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    相关资源
    最近更新 更多