Hello. I'm going through the following scenario. I have a UserControl that has dynamic width based on the text typed in a TextBox inside it. For this in the TextChanged event of this TextBox, the following algorithm is done:
private void MensurarTamanho()
{
var tamanho = TextRenderer.MeasureText(txtLyric.Text, txtLyric.Font).Width + txtLyric.Margin.Horizontal + 2;
var tamanhomin = cbChord.Width + btopc.Width + checkBox1.Width + 6;
Width = tamanho < tamanhomin ? tamanhomin : tamanho;
}
This control is queued within a FlowLayoutPanel (which represents a group of controls) which in turn is Evaletated on another FlowLayoutPanel (that is, a FlowLayoutPanel with FlowLayoutPanels as child controls. In order for the width of the FlowLayoutPanel to fit and be dynamic as the controls are added I have used the following code in the ControlAdded and ControlRemoved events:
private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)
{
var maior = flowLayoutPanel1.Controls.OfType<Control>().OrderBy(c => c.Height).LastOrDefault();
var largura = 6 + flowLayoutPanel1.Controls.OfType<Control>().Sum(c => c.Width + c.Margin.Horizontal);
int altura = 120;
if (maior != null)
{
altura = maior.Height + maior.Margin.Vertical;
}
Size = new Size(largura, altura);
}
This works perfectly when I add and remove controls, however, the internal controls adjust as the text is edited, as described at the beginning. In that case I need to identify when an internal control is resized so that I can apply the resize algorithm above again. I thought of adding a delegate in the Resize event to every child control added and removing the delegate whenever a control is removed, but I'm looking for a more elegant way to do that.