In a MVVM Silverlight application the user can enter text in the TextBox and the ListBox contents changes accordingly. E.g.: If the user enter "TV" the ListBox will populate all the available Television brands and the user can select a product from the ListBox and ListBox entries; next if he enters "computer" ListBox contents change and populate with ComputerNames.
As soon as the user types something it searches in a dictionary with values matching key.
View:
<TextBox Name="SearchTBox" Text="{Binding SearchStr,UpdateSourceTrigger=PropertyChanged}" />
<ListBox Name="AnalysisLBox" ItemsSource="{Binding DataList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding UserSelectedItem,Mode=TwoWay}"
Width="250" BorderBrush="Transparent" SelectedIndex="{Binding LBoxSelectedIndex,Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ViewModel:
SortedDictionary Data()
{
List<string> tvList = new List<string>() { "Sony", "SamSung", "LG","Sharp" };
List<string> computerList = new List<string>() { "HP","Dell","Lenovo","Gateway" };
List<string> cameraList = new List<string>() { "Nikon","Sony","Panasonic" };
SortedDictionary<string, List<string>> Data = new SortedDictionary<string, List<string>>();
Data.Add("TV", billingList);
Data.Add("Computer", salesOutList);
Data.Add("Camera", customerAllocationList);
}
ObservableCollection<string> dataList = new ObservableCollection<string>();
public ObservableCollection<string> DataList
{
get { return dataList ; }
set { dataList = value; NotifyPropertyChanged("DataList"); }
}
int lBoxSelectedIndex;
public int LBoxSelectedIndex
{
get { return lBoxSelectedIndex; }
set { lBoxSelectedIndex = value; NotifyPropertyChanged("LBoxSelectedIndex"); }
}
string userSelectedItem;
public string UserSelectedItem
{
get { return userSelectedItem; }
set
{
userSelectedItem = value;
dataList.Clear();
LBoxSelectedIndex =-1;
NotifyPropertyChanged("UserSelectedItem");
}
}
As soon as a key matches user typed string ('TV') it populates an ObservableCollection<string>
dataList with tvList which is bound to the ListBox. The user types Camera, it clears the dataList and adds cameraList. The problem occurs here. The listBox's selection is not cleared when it clears data and populates with new data. The same item at the previously selected location remain selected.
I tried to set the SelectedIndex to -1 from the UserSelectedItem Property of the ViewModel but it didn't work.