SelectedItem reset when unloading?

2 posts, 0 answers
  1. runer
    runer avatar
    8 posts
    Member since:
    May 2017

    Posted 21 Aug 2017 Link to this post

    I have a RadAutoCompleteBox in RadGridView CellEditTemplate

    public class AutoCompleteCell : RadAutoCompleteBox
        public AutoCompleteCell()
            SelectionMode = AutoCompleteSelectionMode.Single;
            Unloaded += unloaded;
            Loaded += loaded;
        private void loaded(object sender, RoutedEventArgs e)
            //all has value
            string searchText = SearchText;
            object selectedItem = SelectedItem;
        private void unloaded(object sender, RoutedEventArgs e)
            string searchText = SearchText; //has value
            object selectedItem = SelectedItem; //no value


    SearchText is in dropdown ItemsSource, when I click the cell and enter edit mode, Loaded event fired and both SearchText and SelectedItem has value, but when I just press Esc to exit edit mode and in Unloaded event, SearchText still has value but SelectedItem is null.

    Why this happened and how to fix it? Thanks.

    <controls:AutoCompleteCell SelectedItem="{Binding Value, Mode=TwoWay}"  ItemsSource="{Binding Source, Mode=OneWay}" SearchText="{Binding Header, Mode=OneWay}" />


    "Header" is returned from "Value".




  2. Martin
    Martin avatar
    160 posts

    Posted 24 Aug 2017 Link to this post


    I investigated the cause for this behavior and traced it down to a timing issue at the framework binding mechanism. By default, RadAutoCompleteBox clears its selection upon resetting the ItemsSource which in this particular case occurs before the control is unloaded and thus - through the two-way binding the SelectedItem property in your ViewModel is set to null. 

    What I can suggest in this case is to explicitly set the DataContext of the control like so:
    ItemsSource="{Binding Countries}"
    SelectedItem="{Binding SelectedCountry, Mode=TwoWay}"
    SearchText="{Binding Name, Mode=TwoWay}"

    Martin Vatev
    Progress Telerik
    Want to extend the target reach of your WPF applications, leveraging iOS, Android, and UWP? Try UI for Xamarin, a suite of polished and feature-rich components for the Xamarin framework, which allow you to write beautiful native mobile apps using a single shared C# codebase.
Back to Top