0

当我动态创建一个列表框时,这有效..但现在我严格通过 WPF 制作所有内容..这似乎不起作用,我不知道为什么..这对我来说似乎是正确的,我觉得也许我'我错过了什么?

我得到的错误是“对象引用未设置为对象的实例”

wpf代码:

                   <ListBox x:Name="ListBoxT10">
                        <ListBoxItem>
                            <StackPanel Orientation="Horizontal">                                    
                                <TextBox FontSize="14" Text="" Width="120"/>
                                <TextBox FontSize="14" Text="" Width="40" MaxLength="3"/>
                                <TextBox FontSize="14" Text="" Width="413"/>
                            </StackPanel>
                        </ListBoxItem>
                        ...a bunch of the same listboxitems...

C#代码:

            int a = 0;
            foreach (var item in ListBoxT10.Items)
            {
                StackPanel tempStackPanel = item as StackPanel;

                Console.WriteLine(tempStackPanel.Children.Count);  //this even errors.. i guess it's not finding the children

                string pName = (tempStackPanel.Children[0] as TextBox).Text;  //error
                string tri = (tempStackPanel.Children[1] as TextBox).Text;  //error
                string stats = (tempStackPanel.Children[2] as TextBox).Text;  //error

编辑:我意识到这是因为 ListBoxT10.Items 中的项目实际上是“ListBoxItem”的......但现在我无法获得 listboxitems 的孩子......呃 =[

4

1 回答 1

0
                ListBoxItem lbi = (ListBoxItem)(ListBoxT10.ItemContainerGenerator.ContainerFromIndex(a));
                StackPanel sp = lbi.Content as StackPanel;

                string pName = (sp.Children[1] as TextBox).Text;
                string tri = (sp.Children[2] as TextBox).Text;
                string stats = (sp.Children[3] as TextBox).Text;

我忘记了listboxitem ............没想到它也会注册为一个对象

于 2013-10-10T00:45:52.390 回答