我尝试命名,然后为嵌入在ItemsControl中的ComboBox设置DataContext。
在我的主窗口中,我可以按名称访问ItemsControl,但不能访问ItemsControl中的任何元素。
public MainWindow()
{
InitializeComponent();
SList.DataContext = App.SCList; //this is valid
StS.DataContext = App.STList; //this is not
}
这是XAML代码。我可以从程序中访问SList,但不能访问" StS"或" SPanel1"。编译器错误是: "名称' StS'在当前上下文中不存在"
请注意,我已尝试过"姓名"和" x:姓名"
<ScrollViewer VerticalScrollBarVisibility="Auto" >
<ItemsControl Name ="SList" ItemsSource ="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Margin="12"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="3" CornerRadius="5" Margin="8,8" ClipToBounds="True" Background="Beige">
<StackPanel Name="SPanel1">
<StackPanel Orientation="Horizontal">
<Label Content="S Type"/>
<ComboBox Name ="StS" ItemsSource="{Binding Path=ShipType.TypeName, Mode=TwoWay}" DataContext="STList">
</ComboBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Class Name"/>
<TextBox Text="{Binding Path = Name, Mode=TwoWay}" HorizontalAlignment="Center" FontWeight="Bold" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>