private static void OnUnloadedCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is FrameworkElement element && e.NewValue is ICommand command) { if (!Unloaded.Contains(element)) { Unloaded.Add(element); element.Unloaded += (s, a) => { command.Execute(null); Loaded.Remove(element); Unloaded.Remove(element); }; } } }