I currently have a StackPanel, that I am dynamically adding controls to. (Presently other stack panels, DatePickers, ComboBoxes, TextBoxes and Labels.) The intent, is I am trying to dynamically generate search critera options based on the currently selected report type. In doing this I am setting the name so I can access it later, however, I am running into an issue where I can’t seem to get all of the user input controls I want without either missing something or crashing, because StackPanels don’t have a Name property.
// This one crashes because a child StackPanel doesn't have Name
foreach (var child in this.SearchCriteriaStackPanel.Children)
{
switch (((Control)child).Name)
{
case "startDate":
this.reports[index].StartDate = ((DatePicker)child).SelectedDate;
break;
case "endDate":
this.reports[index].EndDate = ((DatePicker)child).SelectedDate;
break;
case "employeeId":
this.reports[index].EmployeeId = (int)((ComboBox)child).SelectedValue != 0 ? (int?)((ComboBox)child).SelectedValue : null;
break;
case "jobNumber":
this.reports[index].JobNumber = ((TextBox)child).Text;
break;
}
}
.
// This one skips over the DatePickers
foreach (var child in this.SearchCriteriaStackPanel.Children)
{
switch (((FrameworkElement)child).Name)
{
case "startDate":
this.reports[index].StartDate = ((DatePicker)child).SelectedDate;
break;
case "endDate":
this.reports[index].EndDate = ((DatePicker)child).SelectedDate;
break;
case "employeeId":
this.reports[index].EmployeeId = (int)((ComboBox)child).SelectedValue != 0 ? (int?)((ComboBox)child).SelectedValue : null;
break;
case "jobNumber":
this.reports[index].JobNumber = ((TextBox)child).Text;
break;
}
}
I’m also open to alternative suggestions on how to solve this problem.
Edit #1:
Here is the initialization and adding of the startDate DatePicker:
var startDateStackPanel = new StackPanel
{
Orientation = Orientation.Horizontal,
Margin = new Thickness(10, 0, 0, 0)
};
startDateStackPanel.Children.Add(new Label { Content = "Start Date:" });
startDateStackPanel.Children.Add(new DatePicker { Width = 120, Name = "startDate" });
this.SearchCriteriaStackPanel.Children.Add(startDateStackPanel);
Edit #2:
I can do this, but it just feels wrong…
var list = new List<Control>(this.SearchCriteriaStackPanel.Children.OfType<DatePicker>());
list.AddRange(this.SearchCriteriaStackPanel.Children.OfType<ComboBox>());
list.AddRange(this.SearchCriteriaStackPanel.Children.OfType<TextBox>());
foreach(var child in list)...
If you are searching for descendants from e.g. FrameworkElement you can replace your for-each loop in the first example with