private void RemoveCardHandler(object sender, RoutedEventArgs e)
{
if (Card == null) return;
// Three cases are possible.
// 1. The container is unloaded (e.g. one closes a GroupWindow).
// This case is recognizable because GroupControl.IsLoaded is false.
// We have to remove our listeners.
// 2. The card is been moved to another group.
// This is recognizable because GroupControl is null.
// We have to remove our listeners.
// 3. The card index changes (e.g. it's moved to top/bottom of a pile).
// In this case WPF seems to unload and then reload the control at the correct position.
// But in some weird cases WPF seems to call Unload WITHOUT a matching Load,
// although the control ends up in the visual tree. E.g. when Moving several cards to the
// top of a pile at once, with the GroupWindow open.
// We can recognize this case because GroupControl.IsLoaded is true.
// In this case we *keep* the listeners attached!
GroupControl groupCtrl = GroupControl;
if (groupCtrl != null && groupCtrl.IsLoaded) return;
Card.PropertyChanged -= PropertyChangeHandler;
img = null;
this.DisplayedPicture = null;
Card = null;
}