My Answer is based on a answer posted for Windows Forms 8+ years back.
I have used the same logic from that answer and created extension method on the Root Grid to loop through and clear values of each element( Mimicking it to bring the UserControl
back to its usual state)
Below is the Extension Method.
public static class Extensions
{
private static Dictionary<Type, Action<UIElement>> controldefaults = new Dictionary<Type, Action<UIElement>>()
{
{typeof(TextBox), c => ((TextBox)c).Text = String.Empty},
{typeof(CheckBox), c => ((CheckBox)c).IsChecked = false},
{typeof(ComboBox), c => ((ComboBox)c).SelectedIndex = 0},
{typeof(ListBox), c => ((ListBox)c).Items.Clear()},
{typeof(RadioButton), c => ((RadioButton)c).IsChecked = false},
};
private static void FindAndInvoke(Type type, UIElement control)
{
if (controldefaults.ContainsKey(type))
{
controldefaults[type].Invoke(control);
}
}
public static void ClearControls(this UIElementCollection controls)
{
foreach (UIElement control in controls)
{
FindAndInvoke(control.GetType(), control);
}
}
public static void ClearControls<T>(this UIElementCollection controls) where T : class
{
if (!controldefaults.ContainsKey(typeof(T))) return;
foreach (UIElement control in controls)
{
if (control.GetType().Equals(typeof(T)))
{
FindAndInvoke(typeof(T), control);
}
}
}
}
For usage, Give the RootGrid Some name. Say rootGrid
. So all you need to call is
rootGrid.Children.ClearControls();
Also As mentioned in other answer, if you want to clear only specific controls, you can use
rootGrid.Children.ClearControls<TextBox>();
You can find the Extensions class on my Gist
Good Luck.