Search code examples
c#wpfxamlcode-behindxname

Code-behind can't find control declared in XAML


After googling for sometime, x:Name should be a solution to my problem.

In my wtfapp.xaml there is a TextBlock that will be created during runtime:

<TextBlock x:Name="wtf" Text="{Binding fTx}"/>

In the code-behind, it should be accessible so I tried to change its Foreground color:

wtf.Foreground = Brushes.DarkGreen;

When I compile, an error shows up:

The name "wtf" does not exist in the current context.

If I'm not mistaken, that means TextBlock "wtf" is not accessible.

How can I resolve the reference?

EDIT:

XAML:

    <DataTemplate x:Key="ItemTemplate_NextAnime_HOVER">
        <Grid Margin="2,0,1,0" Width="82" Height="120" >
            <Image x:Name="NxtAnime_Image" Width="82" Height="120" Stretch="UniformToFill" Panel.ZIndex="0">
                <Image.Source>
                    <BitmapImage UriCachePolicy="Revalidate" UriSource="{Binding rLocalPic}"/>
                </Image.Source>
            </Image>
            <Grid Panel.ZIndex="1" >
                <Border Background="#7F000000" Panel.ZIndex="0" x:Name="brd">
                    <Popup IsOpen="True" StaysOpen="True" PlacementTarget="{Binding ElementName=brd}" Placement="Top">
                        <StackPanel Background="#FFC54B4B" Orientation="Horizontal" Height="334" Width="430">
                            <Image Width="213" Height="326" Stretch="UniformToFill" Margin="4,4,4,6" Source="{Binding LocalPic}"/>
                            <StackPanel Orientation="Vertical" Margin="4,4,4,4" Name="are">
                                <TextBlock Margin="0,0,0,10" Text="{Binding Title}" FontSize="22" Foreground="White" TextWrapping="Wrap" MaxWidth="200" FontWeight="Bold"/>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="Relation: " FontSize="20" Foreground="White"/>
                                    <TextBlock x:Name="wtf" Text="{Binding Type}" FontSize="20" Foreground="White"/>
                                </StackPanel>
                            </StackPanel>
                        </StackPanel>
                    </Popup>
                </Border>
            </Grid>
        </Grid>
    </DataTemplate>

This is a DataTemplate for ListBoxItem.


Solution

  • It's difficult to get an element from a template, as a template is like a factory, and will generate multiple instances.

    As suggested by user2946329 in the comments, ListBox items return string, when DataTemplate is Button answers how to get the element, but there might be another way to do what you want.

    For example, if you want to change the color of the wtf element you can do so with a trigger.

    <DataTemplate.Triggers> <DataTrigger Binding="{Binding ...}" Value="False"> <Setter TargetName="wtf" Property="Foreground" Value="DarkGreen"/> </DataTrigger> </DataTemplate.Triggers>