代码后台找不到在XAML中声明的控件。

4

在搜索了一段时间后,x:Name 应该是解决我的问题的方法。

在我的 wtfapp.xaml 中,有一个 TextBlock 会在运行时创建:

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

在代码后台,应该可以访问它,所以我尝试更改它的前景色:

wtf.Foreground = Brushes.DarkGreen;

当我编译时,出现了一个错误:

当前上下文中不存在“wtf”名称。

如果我没弄错的话,这意味着无法访问TextBlock“wtf”。

我该如何解决此引用?

编辑:

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>

这是一个用于 ListBoxItemDataTemplate


你能提供XAML代码,其中定义了你的TextBlock,这样我们就可以看到上下文吗? - Alex Butenko
这样够了吗?如果需要的话,我可以粘贴整个 XAML,但可能会有问题。 - Wahyu
这取决于你想做什么。你是如何使用弹出窗口的? - Jeff
@CameronMacFarland 噢,你说得对。抱歉误导了你。在这种情况下,如果它不在模板中,我就不知道了。可能是构建问题。 - Jeff
3
要在代码中获取模板中的 TextBlock 并更改其属性,您应该使用 FrameworkTemplate.FindName 方法。请参考此答案:https://dev59.com/5JHea4cB1Zd3GeqPt8YN - Salah Akbari
显示剩余10条评论
1个回答

3

从模板中获取元素很困难,因为模板就像是工厂,会生成多个实例。

如用户user2946329在评论中所建议的,ListBox items return string, when DataTemplate is Button 解答了如何获取元素,但可能还有其他方法来实现你想要的功能。

例如,如果你想要更改 wtf 元素的颜色,可以通过触发器来实现。

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


好的,那我就用这个了 :) - Wahyu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接