MVVM Silverlightアプリケーションでは、ユーザーはTextBoxにテキストを入力でき、それに応じてListBoxの内容が変更されます。例:ユーザーが「TV」と入力すると、リストボックスは利用可能なすべてのテレビブランドに入力され、ユーザーはリストボックスとリストボックスのエントリから製品を選択できます。次に、彼が「コンピューター」と入力すると、リストボックスの内容が変更され、ComputerNamesが入力されます。
ユーザーが何かを入力するとすぐに、キーに一致する値を使用して辞書で検索します。
意見:
<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");
}
}
キーがユーザー入力文字列(「TV」)と一致するとすぐObservableCollection<string>
に、リストボックスにバインドされたtvListをdataListに入力します。ユーザーがCameraと入力すると、dataListがクリアされ、cameraListが追加されます。ここで問題が発生します。listBoxの選択は、データをクリアして新しいデータを入力するときにクリアされません。以前に選択した場所にある同じアイテムが選択されたままになります。ViewModelのUserSelectedItemプロパティからSelectedIndexを-1に設定しようとしましたが、機能しませんでした。