簡體   English   中英

C#中列表框內的列表框

[英]List-box inside a list-box in C#

我在這樣的列表框中有一個列表框。

<ListBox x:Name="listBox1">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel>
            <StackPanel.Background>
               <SolidColorBrush Color="#FF2B3643" Opacity="1"/>
            </StackPanel.Background>
            <StackPanel>
               <TextBlock Text="{Binding X}"/>
               <TextBlock Text="{Binding Y}"/>
            </StackPanel>
            <Button Click="Button_Click">
            <ListBox x:Name="listBox2">
               <ListBox.ItemTemplate>
                  <DataTemplate>
                     <StackPanel>
                        <TextBlock Text="{Binding Name}"/>
                        <TextBlock Text="{Binding Number}"/>
                     </StackPanel>
                  </DataTemplate>
               </ListBox.ItemTemplate>
            </ListBox>
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

當我嘗試綁定內部列表框時,我無法這樣做。

我試過的 c# 代碼如下。

List<Person> p = new List<Person>();

Person student = new Person();
student.Name = "Name1";
student.Number = "Number1";
p.Add(student);

Person teacher = new Person();
teacher.Name = "Name2";
teacher.Number = "Number2";
p.Add(teacher);

listBox2.ItemsSource = p; // cannot access listBox2

但我無法從 xaml.cs 代碼訪問 listBox2。 它說找不到 listBox2。 此外,我只想在單擊按鈕時綁定 listBox2,而不是在綁定 listBox1 時綁定。 有人能告訴我如何訪問 listBox2 嗎?

您已在 listBox1 的DataTemplate中添加了 listBox2。 所以在后面的代碼中將無法訪問它。 詳細說明,假設您在 listBox1 中有 item1、item2 和 item3。 然后您將在 item1、item2 和 item3 中擁有一個名為 listBox2 的 ListBox 對象。 您不能在后面的代碼中明確指出這些對象之一。 實現綁定的一種方法是,在綁定到 listBox1 的項目內創建一個列表,並將其綁定到內部ListBox

List<Item> MainList = new List<Item>();

class Item
{
   List<Person> PersonList = new List<Person>();
}


<ListBox x:Name="listBox1" ItemsSource = "{Binding MainList}">
   <ListBox.ItemTemplate>
      ...
            <ListBox x:Name="listBox2" ItemsSource= "{Binding PersonList}">
               <ListBox.ItemTemplate>
                  ...
               </ListBox.ItemTemplate>
            </ListBox>
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

注意:請參閱此相關問題 - 在 Windows Phone 8 上的列表框中綁定列表框

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM