Я первый раз пишу UI и не могу понять, как работает рендеринг контролов и как сделать так, чтобы нарисованный один раз контрол не перерисовывался каждый раз. Ниже минимальный пример, который должен объяснить, что я хочу и что у меня не получается. Также добавил gif, который наглядно иллюстрирует проблему (по клику на ноду таблицы перерисовываются каждый раз).
Я пробовал несколько вариантов реализации - во всех одинаковая проблема. В той реализации, которую вы можете наблюдать ниже, на главной форме есть TreeView, Tab Page и кнопка Load. Для каждой ноды в Tree View создается свой Flow Panel (с Visible = false по умолчанию). Каждый Flow Panel добавляется в Tab Page. По нажатию на кнопку Load я хочу добавить в Flow Panel каждой ноды какие-то таблицы. Главная форма хранит ссылку на ActiveFlow - тот FlowPanel, который я хочу видеть на Tab Page. По клику на ноду в дереве я хочу видеть таблицы, соответствующие выбранной ноде - я беру Flow Panel выбранной ноды и выставлю для него Visible = true. Кнопка Load здесь служит заменой "загрузки" программы.
Проблема: После клика по ноде в дереве, таблицы каждый раз перерисовываются. Я не понимаю почему и как это прекратить. В данном случае это не так бросается в глаза, но в боевом примере у меня вместо таблиц custom control, который, видимо, намного тяжелее и рисуется дольше.
Помогите, пожалуйста, понять, что я делаю не так и как это исправить.
Node
using System;
using System.Windows.Forms;
namespace AppTest2
{
public class SuperNode : TreeNode
{
public FlowLayoutPanel FlowView { get; }
public SuperNode(String name) : base()
{
this.Name = name;
this.Text = name;
this.FlowView = new FlowLayoutPanel()
{
Visible = false,
Dock = DockStyle.Fill
};
}
}
}
Main Form:
using System;
using System.Windows.Forms;
namespace AppTest2
{
public partial class Form1 : Form
{
Random random = new Random();
public FlowLayoutPanel ActiveFlow { get; internal set; } = null;
public Form1()
{
InitializeComponent();
for (var idx = 0; idx < 3; idx++)
{
var name = "node" + idx.ToString();
var node = new SuperNode(name);
this.treeView1.Nodes.Add(node);
this.tabPage1.Controls.Add(node.FlowView);
}
}
private void buttonLoad_Click(object sender, EventArgs e)
{
foreach (SuperNode node in this.treeView1.Nodes)
{
for (var idx = 0; idx < this.random.Next(5, 10); idx++)
{
var randomTable = this.GetRandomTable();
node.FlowView.Controls.Add(randomTable);
}
}
}
private TableLayoutPanel GetRandomTable()
{
var table = new TableLayoutPanel()
{
CellBorderStyle = TableLayoutPanelCellBorderStyle.Single,
RowCount = this.random.Next(5, 10),
ColumnCount = this.random.Next(5, 10),
AutoSize = true
};
for (var column = 0; column < table.ColumnCount; column++)
{
for (var row = 0; row < table.RowCount; row++)
{
var label = new Label()
{
Dock = DockStyle.Fill,
Text = column.ToString() + row.ToString()
};
table.Controls.Add(label);
}
}
return table;
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (this.treeView1.SelectedNode != e.Node)
{
if (this.ActiveFlow != null)
this.ActiveFlow.Visible = false;
this.ActiveFlow = (e.Node as SuperNode).FlowView;
this.ActiveFlow.Visible = true;
}
}
}
}
Main Form Designer
namespace AppTest2
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.treeView1 = new System.Windows.Forms.TreeView();
this.buttonLoad = new System.Windows.Forms.Button();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabControl1.SuspendLayout();
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Location = new System.Drawing.Point(12, 87);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(212, 441);
this.treeView1.TabIndex = 0;
this.treeView1.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
//
// buttonLoad
//
this.buttonLoad.Location = new System.Drawing.Point(13, 13);
this.buttonLoad.Name = "buttonLoad";
this.buttonLoad.Size = new System.Drawing.Size(211, 53);
this.buttonLoad.TabIndex = 1;
this.buttonLoad.Text = "Load";
this.buttonLoad.UseVisualStyleBackColor = true;
this.buttonLoad.Click += new System.EventHandler(this.buttonLoad_Click);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Right;
this.tabControl1.Location = new System.Drawing.Point(230, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(1074, 821);
this.tabControl1.TabIndex = 2;
//
// tabPage1
//
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(1066, 795);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "tabPage1";
this.tabPage1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1304, 821);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.buttonLoad);
this.Controls.Add(this.treeView1);
this.Name = "Form1";
this.Text = "Form1";
this.tabControl1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.Button buttonLoad;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
}
}