【问题标题】:Code-behind can't find control declared in XAML代码隐藏找不到在 XAML 中声明的控件
【发布时间】:2016-01-03 14:41:42
【问题描述】:

在谷歌上搜索了一段时间后,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>

这是DataTemplateListBoxItem

【问题讨论】:

  • 你需要Name,而不是x:Name
  • @SLaks 它不起作用 :( 你可能想看看这个:stackoverflow.com/questions/13569782/…
  • 那是因为在那个例子中它是一个用户定义的控件。在您的情况下,您需要名称,而不是 x:Name。
  • 能否提供定义文本块的 xaml 代码,以便我们查看上下文?
  • 要在模板中获取TextBlock 并在代码中更改它的属性,您应该使用FrameworkTemplate.FindName 方法。检查这个答案:stackoverflow.com/questions/34117944/…

标签: c# wpf xaml code-behind xname


【解决方案1】:

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

正如 cmets 中的 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>

【讨论】:

  • 很好,我会用这个:)
猜你喜欢
  • 2019-05-26
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
相关资源
最近更新 更多