c# - 错误 : The name 'tBox' does not exist in the current context

标签 c# wpf xaml

错误:名称“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/

相关文章:

c# - 'typeof' 是如何工作的?

c# - 使用套接字的最快下载形式

.net - 无法使用ItemContainerStyle设置菜单项的图标

c# - 有什么方法可以在 XAML 上制作图像映射吗?

c# - 十六进制输出中的扩展工具包的 NumericUpDown

c# - c#中long到decimal的转换

c# - 压缩 c# dnn 模块设置代码

c# - 使 ListBox 大小适合用作 ItemsPresenter 的 ItemsPanel

c# - 在运行时获取对象类型 PRISM MVVM

.net - 使用 PropertyChanged.Fody 构建应用程序时出错