[英]value does not fall within expected range
我正在从事Windows Phone项目。 我有一个列表框,其中包含以下selectionchanged事件处理程序:
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是带有文本块和文本框的用户控件。 CategoryPanel只是一个列表框。
每当更改所选项目时,我都想清除CategoryPanel,并将其替换为新的List。
但是,有时候,当我更改选择时,会出现“值未落在预期范围内”的异常。
我该如何解决?
当您添加多个具有相同名称的控件时,可能会发生这种情况。 试试这个代码。 为了清楚起见,使用换行符进行了细分。 我将其转换为linq语句,并且还将每个LabeledTextBox
命名为随机名称。 注意:我所做的唯一重要的事情是给LabeledTextBox
命名。
Random r = new Random();
void LoadJudgeCategories(string judgeType)
{
CategoryPanel.ItemsSource =
judgeCategories[judgeType]
.Select(cat =>
new LabeledTextBox(cat) { Name = r.Next().ToString() }
).ToList();
}
只是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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.