2014-04-08 89 views
1

我正在开发一个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; 
} 

judgeCategories的类型是

Dictionary<string, string[]> 

LabeledTextBox是用户控件与文本块和一个文本框。 CategoryPanel只是一个列表框。

每当选择的项目发生变化时,我想清除CategoryPanel,并将其替换为新的List。

然而,有时候,当我改变选择时,它会给出例外“值不在预期范围内”。

我该如何解决这个问题?

回答

0

当您添加具有相同名称的多个控件时,可能会发生这种情况。试试这个代码。为了清晰起见,用换行符分解。我把它变成了一个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(); 
} 
+0

不会r.Next()是给予同样的结果两次危险? – phil

+0

不,因为下一个值是从最后一个随机值开始播种的,所以... bassically不,但是如果你想只需要在后面使用一些计数int,那么当它到达int.MaxValue时,只需设置它等于int.MinValue – BenVlodgi

0

只是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)); 
} 
相关问题