public class RadTabItemUnloadBehavior : Behavior { public static void UnloadUserControl(UserControl view) { if (view == null) return; UnloadUsingLogicalTreeHelper(view); view.Resources.Clear(); view.Resources = null; } private static void UnloadUsingLogicalTreeHelper(DependencyObject parent) { if (parent == null) return; List descendants = new List(); CollectLogicalDescendantsInternal(parent, descendants); foreach (DependencyObject dependencyObject in descendants) { ClearProperties(dependencyObject); } } private static void CollectLogicalDescendantsInternal(DependencyObject parent, List list) { if (parent == null) return; foreach (object child in LogicalTreeHelper.GetChildren(parent)) { if (child is DependencyObject depChild) { list.Add(depChild); // Recursive call for the lowest FrameworkElement CollectLogicalDescendantsInternal(depChild, list); } } } private static void ClearProperties(DependencyObject depObj) { ClearStyleSelectors(depObj); if (depObj is Panel panel && !(depObj is ItemsPresenter)) { // If this panel is an ItemsPanel inside an ItemsControl, do not modify its Children if (panel.IsItemsHost) { return; // Do nothing, as WPF controls this panel } panel.Children.Clear(); // Safe to clear only if it's NOT an ItemsHost } else if (depObj is ItemsControl itemsControl) { itemsControl.Items.Clear(); } // Handle ContentControl (e.g., Label, Button, UserControl) else if (depObj is ContentControl) { (depObj as ContentControl).Content = null; } } private static void ClearStyleSelectors(DependencyObject obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); // Get all DependencyProperties from the class and base classes FieldInfo[] fields = obj.GetType().GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy); int i = 0; foreach (FieldInfo field in fields) { if (field.Name.Contains("StyleSelector")) { DependencyProperty dp = field.GetValue(null) as DependencyProperty; if (dp != null) { // Clear the StyleSelector property by setting it to null obj.SetValue(dp, null); dp = null; } } } // Try to remove Events EventInfo[] events = obj.GetType().GetEvents(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (EventInfo eventInfo in events) { try { FieldInfo field = obj.GetType().GetField(eventInfo.Name, BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { // Hole den Delegate, der an das Event gebunden ist Delegate eventDelegate = field.GetValue(obj) as Delegate; if (eventDelegate != null) { foreach (Delegate d in eventDelegate.GetInvocationList()) { eventInfo.RemoveEventHandler(obj, d); } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Fehler beim Entfernen des Events '{eventInfo.Name}': {ex.Message}"); } } } }