错误:名称“tBox”在当前上下文中不存在。
XAML:
<ItemsControl Name="itemsControl">
<ItemsControl.Template>
<ControlTemplate>
<WrapPenel>
<ItemsPresenter/>
</WrapPenel>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Name="tBox" Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
C#:
tBox.Background=Brushes.White; // Error: The name 'tBox' does not exist in the current context.
如何访问控制?
最佳答案
您命名为 tBox 的 TextBlock 位于 DataTemplate 中。模板内的控件位于不同的名称范围内,因此您无法通过其名称在代码隐藏中访问它。我不确定,但您可以通过 ItemTemplate 属性获取它并将其转换为 TextBlock。或者,您可以在表示背景的代码隐藏中添加一个属性,并在 TextBlock 的背景属性上使用绑定(bind)。希望这会有所帮助。
关于c# - 错误 : The name 'tBox' does not exist in the current context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3665996/