我在这样的列表框中有一个列表框。
<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吗?
诀窍是直接绑定到DataContext
。我还需要找到AncestorType
绑定到的UserControl
的DataContext
:
<ListBox ItemsSource="{Binding DialogueEntries}"
SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SelectedDialogueEntryChoice, Mode=TwoWay}">