C# 值不在预期范围内
我正在做一个windows phone项目。我有一个具有以下selectionchanged事件处理程序的列表框:C# 值不在预期范围内,c#,windows-phone-8,C#,Windows Phone 8,我正在做一个windows phone项目。我有一个具有以下selectionchanged事件处理程序的列表框: private void judgeType_SelectionChanged(object sender, SelectionChangedEventArgs e) { LoadJudgeCategories(judgeTypeListBox.SelectedItem.ToString()); } 以下是LoadJudgeCategories方法: void LoadJ
private void judgeType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadJudgeCategories(judgeTypeListBox.SelectedItem.ToString());
}
以下是LoadJudgeCategories方法:
void LoadJudgeCategories(string judgeType)
{
string[] categories = judgeCategories[judgeType];
List<LabeledTextBox> itemSource = new List<LabeledTextBox>();
foreach (string cat in categories)
{
itemSource.Add(new LabeledTextBox(cat));
}
CategoryPanel.ItemsSource = itemSource;
}
判断类别为类型
Dictionary<string, string[]>
LabeledTextBox是带有textblock和textbox的用户控件。CategoryPanel只是一个列表框
无论何时更改所选项目,我都希望清除CategoryPanel,并将其替换为新列表
但是,有时,当我更改选择时,它会给出异常值不在预期范围内
如何修复此问题?添加多个同名控件时,可能会出现这种情况。试试这个代码。为清晰起见,用换行符分解。我将其转换为linq语句,并将每个LabeledTextBox命名为随机。 注意:我做的唯一重要的事情就是给标签文本框起一个名字
只是一个具有ObservableCollection的替代解决方案-无需多次设置CategoryPanel.ItemsSource:
private ObservableCollection<LabeledTextBox> itemSource = new ObservableCollection<LabeledTextBox>();
CategoryPanel.ItemsSource = itemSource; // somewhere in the Constructor
void LoadJudgeCategories(string judgeType)
{
itemSource.Clear();
foreach (string cat in judgeCategories[judgeType])
itemSource.Add(new LabeledTextBox(cat));
}
下一个会不会有两次给出相同结果的危险?不会,因为下一个值是从上一个随机值中去掉的,所以。。。基本上没有,但是如果你想,你可以在后面使用一些计数int,当它达到int.MaxValue时,只需将它设置为int.MinValue
private ObservableCollection<LabeledTextBox> itemSource = new ObservableCollection<LabeledTextBox>();
CategoryPanel.ItemsSource = itemSource; // somewhere in the Constructor
void LoadJudgeCategories(string judgeType)
{
itemSource.Clear();
foreach (string cat in judgeCategories[judgeType])
itemSource.Add(new LabeledTextBox(cat));
}