lundi 11 mai 2015

List-box inside a list-box in C#

I have a list-box inside a list-box like this.

<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>

When I tried to bind the inner list-box, I wasn't able to do so.

The c# code that I tried is as follows.

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

But I cannot access listBox2 from the xaml.cs code. It says listBox2 is not found. Also I want to bind the listBox2 only when the button is clicked and not when binding listBox1. Can someone tell me how do I access listBox2?

Aucun commentaire:

Enregistrer un commentaire