首页 > 解决方案 > For Each 是否引用对象本身或它们的值?

问题描述

这是我的问题:我正在使用ComboBox我的 WPF 应用程序中的一些,我想用 填充它们ComboBoxItemPlus,它们基本上ComboBoxItem还有一些属性,以便更容易地将它们与数据链接起来。我的问题是我想ComboBox自动填充这些。为此,我声明了一个列表ComboBoxItemPlus,将它们一个一个实例化,然后为它们赋予一个像这样的值:(在这种情况下,我可以一个一个地做,因为只有七个,但我必须这样做之后还有更多元素)

 Private Sub FillCBB_Jour()
        Dim item(7) As ComboBoxItemPlus

        For Each it As ComboBoxItemPlus In item
            it = New ComboBoxItemPlus
        Next

        With item(0)
            .Content = New String("Lundi")
            .Value = DayOfWeek.Monday
        End With
        With item(1)
            .Content = New String("Mardi")
            .Value = DayOfWeek.Tuesday
        End With
        With item(2)
            .Content = New String("Mercredi")
            .Value = DayOfWeek.Wednesday
        End With
        With item(3)
            .Content = New String("Jeudi")
            .Value = DayOfWeek.Thursday
        End With
        With item(4)
            .Content = New String("Vendredi")
            .Value = DayOfWeek.Friday
        End With
        With item(5)
            .Content = New String("Samedi")
            .Value = DayOfWeek.Saturday
        End With
        With item(6)
            .Content = New String("Dimanche")
            .Value = DayOfWeek.Sunday
        End With

        For Each it As ComboBoxItemPlus In item
            CBB_Jour.Items.Add(it)
        Next

它返回我以下错误:

System.ArgumentOutOfRangeException
  HResult=0x80131502
  Message=L'index était hors limites. Il ne doit pas être négatif et doit être inférieur à la taille de la collection.
Nom du paramètre : index
  Source=mscorlib
  Arborescence des appels de procédure :
   à System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   à System.Collections.Generic.List`1.get_Item(Int32 index)
   à AutoFHT.DocumentFHTEditor.FillCBB_Jour() dans C:\Users\BOUCKB\Source\Repos\AutoFHT\AutoFHT\DocumentFHTEditor.xaml.vb :ligne 35
   à AutoFHT.DocumentFHTEditor.DocumentFHTEditon_Initialized(Object sender, EventArgs e) dans C:\Users\BOUCKB\Source\Repos\AutoFHT\AutoFHT\DocumentFHTEditor.xaml.vb :ligne 21
   à System.Windows.FrameworkElement.RaiseInitialized(EventPrivateKey key, EventArgs e)
   à System.Windows.FrameworkElement.OnInitialized(EventArgs e)
   à System.Windows.FrameworkElement.TryFireInitialized()
   à System.Windows.FrameworkElement.EndInit()
   à MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)

告诉我 item(0) 没有实例化。

I've try to instanciate them out of the For Each statement, and it works fine. But, again, I'll have to do this with lists I don't know the length, and that's why I want to do it like this.

Can anyone tell me why this doesn't work ?

标签: vb.netforeachcombobox

解决方案


Okay I found the source of my problem.

the For Each statement refers to instanciated objects. In order to make it work, i Used a classic For.


推荐阅读