Wpf 清除列表框MVVM中的选择
在MVVM Silverlight应用程序中,用户可以在文本框中输入文本,列表框的内容也会相应更改。 例如:如果用户输入“TV”,列表框将填充所有可用的电视品牌,用户可以从列表框和列表框条目中选择产品;下一步,如果他进入“计算机”列表框,内容将发生变化,并填充计算机名称 一旦用户键入某个内容,它就会在字典中搜索与键匹配的值 查看:Wpf 清除列表框MVVM中的选择,wpf,silverlight,mvvm,listbox,Wpf,Silverlight,Mvvm,Listbox,在MVVM Silverlight应用程序中,用户可以在文本框中输入文本,列表框的内容也会相应更改。 例如:如果用户输入“TV”,列表框将填充所有可用的电视品牌,用户可以从列表框和列表框条目中选择产品;下一步,如果他进入“计算机”列表框,内容将发生变化,并填充计算机名称 一旦用户键入某个内容,它就会在字典中搜索与键匹配的值 查看: 视图模型: SortedDictionary数据() { List tvList=新列表(){“索尼”、“三星”、“LG”、“夏普”}; List compute
视图模型:
SortedDictionary数据()
{
List tvList=新列表(){“索尼”、“三星”、“LG”、“夏普”};
List computerList=新列表(){“HP”、“Dell”、“Lenovo”、“Gateway”};
List cameraList=新列表(){“尼康”、“索尼”、“松下”};
SortedDictionary数据=新的SortedDictionary();
数据。添加(“电视”,账单列表);
数据。添加(“计算机”,salesOutList);
添加数据(“摄像头”,CustomerLocationList);
}
ObservableCollection dataList=新的ObservableCollection();
公共可观察收集数据列表
{
获取{返回数据列表;}
设置{dataList=value;NotifyPropertyChanged(“dataList”);}
}
int-lBoxSelectedIndex;
公共整数LBoxSelectedIndex
{
获取{return lBoxSelectedIndex;}
设置{lBoxSelectedIndex=value;NotifyPropertyChanged(“lBoxSelectedIndex”);}
}
字符串userSelectedItem;
公共字符串UserSelectedItem
{
获取{return userSelectedItem;}
设置
{
userSelectedItem=值;
dataList.Clear();
LBoxSelectedIndex=-1;
NotifyPropertyChanged(“UserSelectedItem”);
}
}
只要一个键与用户输入的字符串(“TV”)匹配,它就会用绑定到列表框的tvList填充ObservableCollection
数据列表。用户键入Camera,它将清除数据列表并添加cameraList。问题就发生在这里。当列表框清除数据并填充新数据时,它的选择不会被清除。先前选定位置的同一项目保持选中状态。
我试图从ViewModel的UserSelectedItem属性中将SelectedIndex设置为-1,但没有成功。我想您可能混淆了属性。在列表框中进行选择时,将触发
UserSelectedItem
设置程序,清除dataList
,并将LBoxSelectedIndex
设置为-1。因此,当用户从列表框中选择一个项目时,实际发生的情况是,列表框被清除,而没有选择任何内容
相反,当DataList
更改时,您似乎应该清除选择
stringuserselecteditem;
公共字符串UserSelectedItem
{
获取{return userSelectedItem;}
设置
{
userSelectedItem=值;
NotifyPropertyChanged(“UserSelectedItem”);
}
}
ObservableCollection dataList=新的ObservableCollection();
公共可观察收集数据列表
{
获取{返回数据列表;}
设置
{
数据列表=值;
LBoxSelectedIndex=-1;
NotifyPropertyChanged(“数据列表”);
}
}
更新SearchStr
时,您还需要清除DataList
,并且它不等于已排序字典中的任何键
stringsearchstr;
公共字符串SearchStr
{
获取{return searchStr;}
设置
{
searchStr=值;
LBoxSelectedIndex=-1;
if(string.IsNullOrEmpty(searchStr))
DataList=null;
其他的
{
列出所选值;
if(Data.TryGetValue(searchStr,out selectedValue))
DataList=新的ObservableCollection(selectedValue);
其他的
DataList=null;
}
NotifyPropertyChanged(“SearchStr”);
}
}
您还可以在中设置userSelectedItem=null
ObservableCollection<string> dataList = new ObservableCollection<string>();
public ObservableCollection<string> DataList
{
get { return dataList ; }
set
{
dataList = value;
userSelectedItem=null
LBoxSelectedIndex = -1;
NotifyPropertyChanged("DataList");
}
}
ObservableCollection数据列表=新的ObservableCollection();
公共可观察收集数据列表
{
获取{返回数据列表;}
设置
{
数据列表=值;
userSelectedItem=null
LBoxSelectedIndex=-1;
NotifyPropertyChanged(“数据列表”);
}
}
我不明白,当列表框选择发生更改时,是否要清除列表框?用户从列表框中选择项目后,立即清除列表框。