Dockpanel窗口1调用Dockpanel窗口2的listbox控件,用委托,代码实现
时间: 2024-01-05 13:04:46 浏览: 22
假设Dockpanel窗口1为`Form1`,Dockpanel窗口2为`Form2`,其中`Form2`包含一个名为`listBox1`的ListBox控件。
首先,在`Form2`中定义一个委托类型,用来在`Form1`中更新`listBox1`的内容:
```csharp
public delegate void UpdateListBoxDelegate(List<string> items);
```
然后,在`Form2`中定义一个公共方法,用来接收`List<string>`类型的参数,并且使用委托类型来调用`Form1`中的方法更新`listBox1`的内容:
```csharp
public void UpdateListBox(List<string> items)
{
// 使用委托类型来调用Form1中的UpdateListBox方法,更新listBox1的内容
if (this.Owner is Form1 form1)
{
form1.Invoke(new UpdateListBoxDelegate(form1.UpdateListBox), new object[] { items });
}
}
```
在`Form1`中定义一个公共方法`UpdateListBox`,用来更新`listBox1`的内容:
```csharp
public void UpdateListBox(List<string> items)
{
listBox1.Items.Clear();
listBox1.Items.AddRange(items.ToArray());
}
```
最后,在`Form1`中创建`Form2`的实例,并将其`Owner`属性设置为`Form1`,然后使用委托来更新`listBox1`的内容:
```csharp
Form2 form2 = new Form2();
form2.Owner = this;
List<string> items = new List<string>() { "Item 1", "Item 2", "Item 3" };
form2.UpdateListBox(items);
form2.Show();
```
这样,当在`Form2`中调用`UpdateListBox`方法时,就会自动调用`Form1`中的`UpdateListBox`方法更新`listBox1`的内容。