开发者

Error: The name 'tBox' does not exist in the current context

Error: The name 'tBox' does not exist in the current context.

XAML:

<ItemsControl Name="itemsControl">
开发者_StackOverflow    <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.

How to access control?


The TextBlock you named tBox is inside a DataTemplate. Controls inside a template are in a different name scope, so you can't access it in code-behind via its name. I'm not sure but you might get it via the ItemTemplate property and casting it to a TextBlock. Or you can add a property in your code-behind representing the background and use binding on the TextBlock's Background property. Hope this helps.


Set it on the TextBlock, in your DataTemplate:

<DataTemplate>
    <TextBlock Name="tBox" Background="White" Text="{Binding Name}"></TextBlock>
</DataTemplate>

Or if you wish to only set the Background in certain conditions, consider using Triggers:

<DataTemplate>
    <TextBlock Name="tBox" Text="{Binding Name}"></TextBlock>
    <DataTemplate.Triggers>
        <Trigger SourceName="tBox" Property="IsMouseOver" Value="True">
            <Setter TargetName="tBox" Property="Background" Value="White" />
        </Trigger>
    </DataTemplate.Triggers>
</DataTemplate>

More information on how to use Triggers can be found here: A Guided Tour of WPF - Part 4 (Data Templates and Triggers)


I didn't try but maybe the answer here works:

Access a control from within a DataTemplate with its identifying name

to use something like :

var tbUserIcon= (TextBlock)checkBox.Template.FindName("tbUserIcon", checkBox);

But I think this way isn't convenient at all, especially if there's lots of controls have to do it this way, and it can't be checked by intellisense when writing code real time.


this.Background=Brushes.White; (assuming its code behind the control)?


Since Background is a dependency property, you will have to use

tBox.SetValue(BackgroundProperty, new SolidBrush(Color.White));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜