C# C中的引用TextBlock元素#

C# C中的引用TextBlock元素#,c#,xaml,datatemplate,C#,Xaml,Datatemplate,我的XAML页面中有一个带有数据绑定的数据模板。此数据模板直接驻留在XAML页面上,它不被其他结构(如GridView或ListView)引用。它不用作ItemTemplate <DataTemplate x:Name="Standard250x480ItemTemplate"> <Grid HorizontalAlignment="Left" Width="250" Height="480" Margin="0 0 0 0"> &

我的XAML页面中有一个带有数据绑定的数据模板。此数据模板直接驻留在XAML页面上,它不被其他结构(如GridView或ListView)引用。它不用作ItemTemplate

<DataTemplate x:Name="Standard250x480ItemTemplate">
        <Grid HorizontalAlignment="Left" Width="250" Height="480" Margin="0 0 0 0">
            <!--<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">-->
            <Border Background="#ffffff">
                <Image Source="{Binding Image}" Stretch="Uniform" AutomationProperties.Name="{Binding Title}" />
            </Border>

            <StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
                <TextBlock x:Name="Title" TextAlignment="Center"  Padding="0 18 0 0" FontSize="25" Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="60" Margin="15,0,15,0" />
                <!--<TextBlock Text="{Binding Subtitle}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>-->
            </StackPanel>
        </Grid>

    </DataTemplate>
无法识别文本块。我以前使用过这个,它工作得很好,但不是在数据模板中

我想在单击功能中使用名为“Title”的文本块中的
Text
属性的任何值,以便我可以将其传递到应用程序中的另一个页面。为此,我需要获取TextBlock的文本值


我做错了什么?如何处理数据模板中的元素?

因为标题包含在数据模板中,所以无法从代码后面引用它。如果将此模板包含在列表框中,该怎么办;可能有几个标题文本块

为了从代码隐藏中查找数据模板,您可以使用以下方法:

this.TryFindResource("Standard250x480ItemTemplate");
然后必须将其转换为DataTemplate,然后必须使用VisualTreeHelper或LogicalTreeHelper来查找TextBlock

最好的解决方案是使用ViewModel对象(我看到您使用的是Text=“{Binding Title}”)。从列表框中获取项目或从ContentControl中获取内容,可以将其强制转换到ViewModel实例中,如下所示:

var viewModel = (MyViewModel)listBox.SelectedItem;
var title = viewModel.Title;

您不能使用Title的名称,因为它由演示表单本身使用

为避免在将来使用时出现这种情况,请执行以下操作:


TextBoxTitle或类似的东西

你能分享一些关于你想要达到的目标的更多细节吗?我在上面做了一些编辑。这有帮助吗?如果DataTemplate没有在任何迭代控件(如gridview、listview等)中使用,我不明白为什么要使用DataTemplate。如果我理解正确,最好将其设置为UserControl,但我可能误解了您的问题。您不需要使用c来创建绑定(无需强制转换)。
var viewModel = (MyViewModel)listBox.SelectedItem;
var title = viewModel.Title;