SelectedItem of RadListBox reset when unloading?

1 Answer 22 Views
ListBox
Raphael
Top achievements
Rank 1
Raphael asked on 21 May 2025, 11:35 AM
Hello!

I have exactly this problem reported on this post: https://www.telerik.com/forums/selecteditem-reset-when-unloading but using RadListBox.

Do you know of any solutions other than setting DataContext explicitly? This workaround worked on some controls but not on others.

1 Answer, 1 is accepted

Sort by
0
Martin Ivanov
Telerik team
answered on 26 May 2025, 10:27 AM

Hello Raphael,

As stated in the forum, this is a timing problem. It can be observed in different selector controls in WPF. Basically, in some situation when a selector gets unloaded its ItemsSource setting gets cleared before the data context is detached, which triggers the SelectedItem binding. Because the ItemsSource is null or empty at this point, this tells the control no meaningful selection is presented, thus clearing the SelectedItem as well.

To resolve this, you can use the solution from the forum. In other words, explicitly binding the DataContext of the RadListBox.

  <telerik:GridViewDataColumn.CellEditTemplate>
      <DataTemplate>
          <telerik:RadListBox DataContext="{Binding}" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"/>
      </DataTemplate>
  </telerik:GridViewDataColumn.CellEditTemplate>

I've tested this and it seems to work properly on my side. Can you try it and let me know if I am missing anything? 

An alternative solution would be to handle the DataContextChanged event of RadListBox. This will allow you to clear the SelectedItem binding on Unloaded.

public class CustomListBox : RadListBox
{
    public CustomListBox()
    {
        DataContextChanged += CustomListBox_DataContextChanged;   
    }

    private void CustomListBox_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue == null)
        {
            BindingOperations.ClearBinding(this, RadListBox.SelectedItemProperty);
        }        
    }
}

Regards,
Martin Ivanov
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
ListBox
Asked by
Raphael
Top achievements
Rank 1
Answers by
Martin Ivanov
Telerik team
Share this question
or