A list is to be displayed using the RadTreeListView. It should be possible to add a single element or to delete several selected elements. As soon as a new element is added, all other elements should be deselected and the new element should be selected.
The problem is that if a certain number of elements is deleted, afterwards just as many newly added elements are automatically deselected, although they were previously explicitly selected programmatically.
Example with test application
Initial state:
→ Click "Add" to add a new element:
→ Click "Delete" to delete selected element (for simplicity the automatically selected element just added is used):
→ Click "Add" to add a new element:
Element 4 should now be selected.
→ Click "Add" to add a new element:
Now it works again as expected.
The same behavior can be replicated with deleting multiple elements. Afterwards, exactly this number of then newly added elements are deselected, although they should be selected. After that the behavior is as expected again.
View
<StackPanel>
<Button Click="Add_Button_Click">Add</Button>
<Button Click="Delete_Button_Click">Delete</Button>
<telerik:RadTreeListView ItemsSource="{Binding VM.Elements}"
SelectionMode="Multiple"
IsSynchronizedWithCurrentItem="False"
RowIndicatorVisibility="Collapsed"
>
<telerik:RadTreeListView.RowStyle>
<Style TargetType="{x:Type telerik:TreeListViewRow}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</telerik:RadTreeListView.RowStyle>
</telerik:RadTreeListView>
</StackPanel>
CodeBehind
public partial class MainWindow : Window
{
public ViewModel VM { get; set; }
public MainWindow()
{
InitializeComponent();
VM = new ViewModel();
DataContext = this;
}
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
VM.AddNewData();
}
private void Delete_Button_Click(object sender, RoutedEventArgs e)
{
VM.Elements.RemoveAll(x => x.IsSelected);
}
}
ViewModel
public class ViewModel
{
public ObservableCollection<Data> Elements { get; set; } = new ObservableCollection<Data>();
public ViewModel()
{
Enumerable.Range(0, 3).ForEach(_ => AddNewData());
Elements.CollectionChanged += Data_CollectionChanged;
}
public void AddNewData()
{
Elements.Add(new Data());
}
private void Data_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
Elements.ForEach(x => x.IsSelected = false);
e.NewItems?.OfType<Data>().ForEach(x => x.IsSelected = true);
}
}
public class Data : INotifyPropertyChanged
{
static private int counter = 0;
public event PropertyChangedEventHandler? PropertyChanged;
private bool isSelected = false;
public bool IsSelected
{
get
{
return isSelected;
}
set
{
isSelected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
public int Id { get; set; } = counter++;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}