面板控制不更新

Panel Control doesn't update

我的页面上有面板对象,我想用另一个面板替换它

//Info.panel[cb_page_number.SelectedIndex] = pnl_page_active;
Panel new_panel = new Panel();
new_panel.BackColor = Color.White;
//new_panel.Name ="page_"+ (cb_page_number.SelectedIndex+1).ToString();
//cb_page_number.Items.Add(new_panel.Name);
//cb_page_number.SelectedIndex = cb_page_number.Items.Count-1;
pnl_page_active = new_panel;
pnl_page_active.Refresh();
pnl_page_active.Update();
Application.DoEvents();

pnl_page_active 背景色为象牙色,上面有一些控件。当我执行上面的代码时,我 expext 看到 pnl_page_active 背景已经改变并且没有控制,但它是一样的,所以我想知道问题是什么?

您所做的只是将 new_panel 变量分配给 pnl_page_active。它与控制层次结构无关。

您需要从其父面板中删除旧面板并插入新面板:

Control parent = pnl_page_active.Parent;
if (parent != null) {
    parent.Controls.Remove(pnl_page_active);
    parent.Controls.Add(new_panel);
}

您当前正在做的是修改 pnl_page_active 以引用与 new_panel 相同的面板...但是 new_panel 从未添加到表单中,因此您不需要看不到颜色变化。

删除上面所有的代码,直接更改BackColor

pnl_page_active.BackColor = Color.White;

如果您想用新的面板替换现有的面板(无论出于何种原因),您必须确保它具有相同的父级、大小、位置等,此外还有您想要的任何属性正在复制。

Panel new_panel = new Panel();
new_panel.BackColor = Color.White;
new_panel.Size = pnl_page_active.Size;
new_panel.Location = pnl_page_active.Location;
new_panel.Parent = pnl_page_active.Parent;
new_panel.Show();

pnl_page_active.Hide();  // or Dispose if you don't want it anymore