V svojom nižšie uvedenom programe sa po nagenerovaní textBoxov a buttonov po kliknutí na nagenerovaný buton zafarbia textBoxy. Po kliknutí na iný button sa zafarbia ďalšie textBoxy, ale zostanú zafarbené aj tie predošlé u ktorých by farba sa mala zmeniť na pôvodnú. Poradí mi niekto prosím, ako to mám urobiť? Nejako cez foreach, ale neviem ako.
public partial class MainWindow : Window
{
int textBoxCislo =1;
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
GenerateTextBox();
}
private void GenerateTextBox()
{
var panel = new StackPanel() { Orientation = Orientation.Horizontal };
var textbox = new TextBox() { Name = "a" + textBoxCislo.ToString(), Text = textBoxCislo.ToString(), Width = 20 };
panel.Children.Add(textbox);
textbox = new TextBox() { Name = "b" + textBoxCislo.ToString(), Text = textBoxCislo.ToString(), Width = 20 };
panel.Children.Add(textbox);
var btnX = new Button() { Name = "btn" + textBoxCislo.ToString(), Tag= textBoxCislo.ToString() };
btnX.Click +=btnX_Click;
panel.Children.Add(btnX);
stackPanel1.Children.Add(panel);
this.textBoxCislo++;
}
private void btnX_Click(object sender, RoutedEventArgs e)
{
var panel = (DependencyObject)VisualTreeHelper.GetParent((DependencyObject)sender);
TextBox textBoxA = null;
TextBox textBoxB = null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(panel); i++)
{
var element = (FrameworkElement)VisualTreeHelper.GetChild(panel, i);
if (element.Name.StartsWith("a"))
{
textBoxA = (TextBox)element;
textBoxA.Background = new SolidColorBrush(Colors.Aqua);
}
if (element.Name.StartsWith("b") && !element.Name.StartsWith("btn"))
{
textBoxB = (TextBox)element;
textBoxB.Background = new SolidColorBrush(Colors.Aqua);
}
}
MessageBox.Show(textBoxA.Text + " " + textBoxB.Text);
}
}
|