From 050e4f5b6f07a026ea451ce0f38406430b3efad3 Mon Sep 17 00:00:00 2001 From: Lorenz Stechauner Date: Fri, 14 Jun 2024 13:24:00 +0200 Subject: [PATCH] ControlUtils: Allow RenewItemsSource for ListBox to reselect all items --- Elwig/Helpers/ControlUtils.cs | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/Elwig/Helpers/ControlUtils.cs b/Elwig/Helpers/ControlUtils.cs index 89f210a..45c2bdf 100644 --- a/Elwig/Helpers/ControlUtils.cs +++ b/Elwig/Helpers/ControlUtils.cs @@ -134,19 +134,31 @@ namespace Elwig.Helpers { public static void RenewItemsSource(ListBox listBox, IEnumerable? source, SelectionChangedEventHandler? handler = null, RenewSourceDefault def = RenewSourceDefault.None) { if (listBox.ItemsSource == source) return; - var selectedId = Utils.GetEntityIdentifier(listBox.SelectedItem); - object? selItem = null; - if (selectedId != 0 && source != null) - selItem = source.Cast().FirstOrDefault(i => selectedId.Equals(Utils.GetEntityIdentifier(i))); - if (source != null && selItem == null) { - if ((def == RenewSourceDefault.IfOnly && source.Cast().Count() == 1) || def == RenewSourceDefault.First) { - selItem = source.Cast().FirstOrDefault(); + if (listBox.SelectionMode == SelectionMode.Single) { + var selectedId = Utils.GetEntityIdentifier(listBox.SelectedItem); + object? selItem = null; + if (selectedId != 0 && source != null) + selItem = source.Cast().FirstOrDefault(i => selectedId.Equals(Utils.GetEntityIdentifier(i))); + if (source != null && selItem == null) { + if ((def == RenewSourceDefault.IfOnly && source.Cast().Count() == 1) || def == RenewSourceDefault.First) { + selItem = source.Cast().FirstOrDefault(); + } } + if (handler != null && selItem != null) listBox.SelectionChanged -= handler; + listBox.ItemsSource = source; + if (handler != null && selItem != null) listBox.SelectionChanged += handler; + listBox.SelectedItem = selItem; + } else { + var selectedIds = listBox.SelectedItems.Cast().Select(Utils.GetEntityIdentifier).ToList(); + if (handler != null && selectedIds != null) listBox.SelectionChanged -= handler; + listBox.ItemsSource = source; + if (source != null && selectedIds != null) { + listBox.SelectedItems.Clear(); + foreach (var i in source.Cast().Where(i => selectedIds.Contains(Utils.GetEntityIdentifier(i)))) + listBox.SelectedItems.Add(i); + } + if (handler != null && selectedIds != null) listBox.SelectionChanged += handler; } - if (handler != null && selItem != null) listBox.SelectionChanged -= handler; - listBox.ItemsSource = source; - if (handler != null && selItem != null) listBox.SelectionChanged += handler; - listBox.SelectedItem = selItem; } public static object? GetItemFromSource(IEnumerable source, int? hash) {