在 MVVM Silverlight 应用程序中,用户可以在 TextBox 中输入文本,并且 ListBox 内容会相应更改。
例如:如果用户输入“TV”,列表框将填充所有可用的电视品牌,并且用户可以从列表框和列表框条目中选择产品;接下来,如果他输入“计算机”,则列表框内容会更改并用计算机名称填充。
一旦用户输入内容,它就会在字典中搜索具有与键匹配的值的内容。
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>
视图模型:
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>
dataList 和 tvList 绑定到 ListBox。用户输入Camera,它会清除dataList并添加cameraList。问题就出现在这里。当清除数据并填充新数据时,列表框的选择不会被清除。先前选择的位置处的相同项目仍保持选中状态。
我尝试将 ViewModel 的 UserSelectedItem 属性中的 SelectedIndex 设置为 -1,但它不起作用。