If you have access to templatedparent (SelectedItem, FindVisualParent, etc.), you can do this if you apply the names to the text fields. Example if the ControlTemplate is for ComboBoxItem.
private void AddUser_Click(object sender, RoutedEventArgs e) { ComboBoxItem comboBoxItem = GetVisualParent<ComboBoxItem>(button); TextBox textBox = comboBoxItem.Template.FindName("numberTextBox", comboBoxItem) as TextBox;
Another way to get TextBoxes in a ControlTemplate would be to use Visual Tree. Something like that
private void AddUser_Click(object sender, RoutedEventArgs e) { Button button = sender as Button; Grid parentGrid = GetVisualParent<Grid>(button); List<TextBox> textBoxes = GetVisualChildCollection<TextBox>(parentGrid); foreach (TextBox textBox in textBoxes) { if (textBox.Tag == "Number") { // Do something.. } else if (textBox.Tag == "Login") { // Do something.. } else if (textBox.Tag == "Password") { // Do something.. } } }
And the implementation of GetVisualParent and GetVisualChildCollection
public static T GetVisualParent<T>(object childObject) where T : Visual { DependencyObject child = childObject as DependencyObject; // iteratively traverse the visual tree while ((child != null) && !(child is T)) { child = VisualTreeHelper.GetParent(child); } return child as T; } public static List<T> GetVisualChildCollection<T>(object parent) where T : Visual { List<T> visualCollection = new List<T>(); GetVisualChildCollection(parent as DependencyObject, visualCollection); return visualCollection; } private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual { int count = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < count; i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); if (child is T) { visualCollection.Add(child as T); } else if (child != null) { GetVisualChildCollection(child, visualCollection); } } }
source share