【发布时间】:2017-10-31 13:57:18
【问题描述】:
在我的列表框中显示列表时遇到了一些麻烦。 当我在一堂课上拥有一切时,一切似乎都很好,但我不知道为什么它现在不起作用。当单击扫描按钮时,我的应用程序转到另一个类,其中创建了一个新线程来扫描可用的蓝牙设备,并创建了包含这些设备的列表。一旦列表被传递回 Form1 类中的方法,它就不会更新列表框。在调试模式下,我可以看到列表中有项目,但列表框中没有任何内容。如果我从扫描按钮单击方法执行 listBox1.Items.Add("Hello World") ,则列表框会显示项目。我有点卡在这里。我刚刚开始学习 C#,如果有人可以帮助我,我将不胜感激。
public partial class Form1 : Form
{
int PanelWidth;
bool PanelCalShow;
public Form1()
{
InitializeComponent();
PanelWidth = PanelCal.Width;
PanelCalShow = false;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (PanelCalShow)
{
PanelCal.Width = PanelCal.Width + 10;
if (PanelCal.Width >= PanelWidth)
{
timer1.Stop();
PanelCalShow = false;
this.Refresh();
}
}
else
{
if (PanelCalShow != true)
{
PanelCal.Width = PanelCal.Width - 10;
if (PanelCal.Width <= 0)
{
timer1.Stop();
PanelCalShow = true;
this.Refresh();
}
}
}
}
// Bluetooth connection
private void BtnScan_Click(object sender, EventArgs e)
{
var instance = new BtCom();
instance.Scan();
}
public void LbClientUpdate(List<string> DiscoveredDevices)
{
listBox1.DataSource = DiscoveredDevices;
}
}
和蓝牙连接类
public class BtCom
{
public List<string> DiscoveredDevices = new List<string>();
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
public void Scan()
{
Thread bluetoothScanThread = new Thread(new ThreadStart(Scanning));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
public void Scanning()
{
var form1 = new Form1();
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo d in devices)
{
DiscoveredDevices.Add(d.DeviceName);
}
form1.LbClientUpdate(DiscoveredDevices);
}
}
【问题讨论】:
-
你有一个函数
LbClientUpdate来设置ListBox的DataSource,但是它不是从任何地方调用的。 -
您在原始表单上没有看到任何更新的原因是您正在 BtCom 类中创建
Form1类的新实例,而不是使用原始实例。 -
嗨,对不起。我正在删除 cmets,并且必须也删除了它。我在 listBox1.DataSource 之后有一个带有“hello world”的消息框,它会像它应该弹出的那样弹出,但列表框中没有任何内容。可能是因为该方法是从不同的线程调用的,因此它也在该线程中执行,并且据我所知,应该从其原始线程中编辑列表框?