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<object>().FirstOrDefault(i => selectedId.Equals(Utils.GetEntityIdentifier(i))); - if (source != null && selItem == null) { - if ((def == RenewSourceDefault.IfOnly && source.Cast<object>().Count() == 1) || def == RenewSourceDefault.First) { - selItem = source.Cast<object>().FirstOrDefault(); + if (listBox.SelectionMode == SelectionMode.Single) { + var selectedId = Utils.GetEntityIdentifier(listBox.SelectedItem); + object? selItem = null; + if (selectedId != 0 && source != null) + selItem = source.Cast<object>().FirstOrDefault(i => selectedId.Equals(Utils.GetEntityIdentifier(i))); + if (source != null && selItem == null) { + if ((def == RenewSourceDefault.IfOnly && source.Cast<object>().Count() == 1) || def == RenewSourceDefault.First) { + selItem = source.Cast<object>().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<object>().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<object>().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) {