private void RecalculateLanes() { if (Application.Current.MainWindow.Dispatcher.CheckAccess()) { if (_recalculatingLanes) { return; } _recalculatingLanes = true; var currentlyDragging = Application.Current.MainWindow.FindVisualChildren <TimeslotControl>().Where(x => x.HoldingStart || x.HoldingEnd).Select(x => x.Model); foreach (var lane in Lanes.ToList()) { var overlappers = lane.Items.Where(x => x.OverlapsAny(lane.Items)).Except(currentlyDragging).ToList(); while (overlappers.Count > 0) { lane.Items.Remove(overlappers.First()); var newLane = new TimelineLaneModel() { LaneNumber = Lanes.Count + 1 }; newLane.Items.Add(overlappers.First()); Lanes.Add(newLane); overlappers = lane.Items.Where(x => x.OverlapsAny(lane.Items)).ToList(); } } foreach (var lane in Lanes.OrderByDescending(x => x.LaneNumber).ToList()) { foreach (var item in lane.Items.ToList()) { foreach (var lane2 in Lanes.Where(x => x.LaneNumber < lane.LaneNumber).ToList()) { if (!item.OverlapsAny(lane2.Items)) { if (currentlyDragging.Contains(item)) { foreach (var item2 in lane2.Items.ToList()) { lane.Items.Add(item2); lane2.Items.Remove(item2); } } else { lane2.Items.Add(item); lane.Items.Remove(item); } } } } } foreach (var lane in Lanes.ToList()) { if (lane.Items.Count == 0) { Lanes.Remove(lane); } } foreach (var lane in Lanes) { lane.LaneNumber = Lanes.IndexOf(lane); } RaisePropertyChanged("Lanes"); _recalculatingLanes = false; } else { Application.Current.MainWindow.Dispatcher.Invoke(RecalculateLanes); } }