ControlUtils: Allow RenewItemsSource for ListBox to reselect all items
All checks were successful
Test / Run tests (push) Successful in 2m21s

This commit is contained in:
2024-06-14 13:24:00 +02:00
parent 01f055ee17
commit 050e4f5b6f

View File

@ -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) {