This is a migrated thread and some comments may be shown as answers.

SelectedItem reset when unloading?

1 Answer 156 Views
AutoCompleteBox
This is a migrated thread and some comments may be shown as answers.
runer
Top achievements
Rank 1
runer asked on 22 Aug 2017, 04:05 AM

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".

 

 

 

1 Answer, 1 is accepted

Sort by
0
Martin
Telerik team
answered on 24 Aug 2017, 10:24 AM
Hi,

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:
<telerik:RadAutoCompleteBox
ItemsSource="{Binding Countries}"
DataContext="{Binding}"
DisplayMemberPath="Name"
Unloaded="RadAutoCompleteBox_Unloaded"
Loaded="RadAutoCompleteBox_Loaded"
SelectedItem="{Binding SelectedCountry, Mode=TwoWay}"
SearchText="{Binding Name, Mode=TwoWay}"
SelectionMode="Single"/>

Regards,
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 you to write beautiful native mobile apps using a single shared C# codebase.
Tags
AutoCompleteBox
Asked by
runer
Top achievements
Rank 1
Answers by
Martin
Telerik team
Share this question
or