簡體   English   中英

后台代碼找不到XAML中聲明的控件

[英]Code-behind can't find control declared in XAML

谷歌搜索一段時間后, 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

從模板中獲取元素非常困難,因為模板就像工廠一樣,並且會生成多個實例。

正如user2946329在注釋中所建議的那樣,當DataTemplate為Button回答如何獲取元素ListBox項目返回字符串 ,但是可能還有另一種方法來執行所需的操作。

例如,如果要更改wtf元素的顏色,可以使用觸發器進行更改。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM