How do I loop through the all controls in a window in WPF?
NavigationService is for browser navigation within WPF. What you are trying to do is change to a different window TrainingFrm . To go to a different window, you should do this: private void conditioningBtn_Click(object sender, RoutedEventArgs e) { var newForm = new TrainingFrm(); //create your new form.
The proper way to shutdown a WPF app is to use Application. Current. Shutdown() . This will close all open Window s, raise some events so that cleanup code can be run, and it can't be canceled.
WPF SDK continues to use the term "control" to loosely mean any class that represents a visible object in an application, it is important to note that a class does not need to inherit from the Control class to have a visible presence.
I found this in the MSDN documenation so it helps.
// Enumerate all the descendants of the visual object. static public void EnumVisual(Visual myVisual) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++) { // Retrieve child visual at specified index value. Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i); // Do processing of the child visual object. // Enumerate children of the child visual object. EnumVisual(childVisual); } }
Looks simpler to me. I used it to find textboxes in a form and clear their data.
This way is superior to the MSDN method, in that it's reusable, and it allows early aborting of the loop (i.e. via, break;
, etc.) -- it optimizes the for loop in that it saves a method call for each iteration -- and it also lets you use regular for loops to loop through a Visual's children, or even recurse it's children and it's grand children -- so it's much simpler to consume.
To consume it, you can just write a regular foreach loop (or even use LINQ):
foreach (var ctrl in myWindow.GetChildren()) { // Process children here! }
Or if you don't want to recurse:
foreach (var ctrl in myWindow.GetChildren(false)) { // Process children here! }
To make it work, you just need put this extension method into any static class, and then you'll be able to write code like the above anytime you like:
public static IEnumerable<Visual> GetChildren(this Visual parent, bool recurse = true) { if (parent != null) { int count = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < count; i++) { // Retrieve child visual at specified index value. var child = VisualTreeHelper.GetChild(parent, i) as Visual; if (child != null) { yield return child; if (recurse) { foreach (var grandChild in child.GetChildren(true)) { yield return grandChild; } } } } } }
Also, if you don't like recursion being on by default, you can change the extension method's declaration to have recurse = false
be the default behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With