J'ai un formulaire Mdiparent contenant un bouton et certaines formes enfants. Comment est-il possible de changer backcolor de toutes les zones de texte dans tous les formulaires enfant lorsque vous cliquez sur le bouton dans le formulaire parent?comment modifier les propriétés des contrôles de formulaire enfant sous forme parent
Répondre
Ceci le ChilForm
;
public ChilForm()
{
InitializeComponent();
}
public void ChangeTextboxColor()
{
textBox1.BackColor = Color.Yellow;
}
Et ceci est Parent
;
ChilForm frm = new ChilForm();
public Parent()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Shows the child
frm.Show();
}
private void button2_Click(object sender, EventArgs e)
{
//Changes color
frm.ChangeTextboxColor();
}
Bien que cela fonctionnera, il vous faudra instancier toutes les formes enfants et appeler leurs méthodes indépendamment. Une alternative à ceci serait d'utiliser le modèle observable ou au moins d'utiliser des événements. –
Oui, ça marche, merci Irshad. :) – Behnam
Je sais que la réponse est déjà donnée .. mais j'aller avec l'événement et les délégués .. délégué multicast est le meilleur choix est ici alors voici ma solution.
namespace winMultiCastDelegate
{
public partial class Form1 : Form
{
public delegate void ChangeBackColorDelegate(Color backgroundColor);
//just avoid null check instanciate it with fake delegate.
public event ChangeBackColorDelegate ChangeBackColor = delegate { };
public Form1()
{
InitializeComponent();
//instanciate child form for N time.. just to simulate
for (int i = 0; i < 3; i++)
{
var childForm = new ChildForm();
//subscribe parent event
this.ChangeBackColor += childForm.ChangeColor;
//show every form
childForm.Show();
}
}
private void button1_Click(object sender, EventArgs e)
{
ChangeBackColor.Invoke(Color.Black);
}
}
/// <summary>
/// child form class having text box inside
/// </summary>
public class ChildForm : Form
{
private TextBox textBox;
public ChildForm()
{
textBox = new TextBox();
textBox.Width = 200;
this.Controls.Add(textBox);
}
public void ChangeColor(Color color)
{
textBox.BackColor = color;
}
}
}
Rendre toutes les zones de texte publiques au format enfant et y accéder en appelant le formulaire enfant à partir du parent. – Irshad
Je devrais appeler chaque zone de texte séparément? – Behnam
Ecrivez une méthode au format enfant et appelez-la. Ensuite, pas besoin de définir le modificateur 'public' pour les zones de texte. – Irshad