【发布时间】: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>
这是DataTemplate 的ListBoxItem。
【问题讨论】:
-
你需要
Name,而不是x:Name。 -
@SLaks 它不起作用 :( 你可能想看看这个:stackoverflow.com/questions/13569782/…
-
那是因为在那个例子中它是一个用户定义的控件。在您的情况下,您需要名称,而不是 x:Name。
-
能否提供定义文本块的 xaml 代码,以便我们查看上下文?
-
要在模板中获取
TextBlock并在代码中更改它的属性,您应该使用FrameworkTemplate.FindName方法。检查这个答案:stackoverflow.com/questions/34117944/…
标签: c# wpf xaml code-behind xname