2016-01-03 61 views
1

宣佈谷歌搜索了一段時間後,控制,x:Name應該是我的問題的解決方案。代碼隱藏找不到XAML

在我wtfapp.xaml存在,將在運行時創建一個TextBlock

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

在代碼隱藏,它應該是可訪問的,所以我試圖改變它的前景色:

wtf.Foreground = Brushes.DarkGreen; 

當我編譯,錯誤顯示出來:

名稱「跆拳道」並不在當前CON存在文本。

如果我沒有弄錯,那就意味着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

+0

您需要名稱而不是'x:Name'。 – SLaks

+0

@SLaks不起作用:(你可能想看到這個:http://stackoverflow.com/questions/13569782/how-to-access-control-in-code-behind-that-was-created-in 。-xaml – Wahyu

+0

這是因爲在這個例子是一個用戶定義的控制你的情況,你想要的名稱,不是X:?名稱 – Jeff

回答

1

這是很難從模板獲取元素,作爲模板就像一個工廠,並會生成多個實例。

正如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>

+0

不錯,我會用這個:) – Wahyu