如何在DataTemplate中选择单个TextBlock

本文关键字:选择 单个 TextBlock DataTemplate | 更新日期: 2023-09-27 17:50:38

我的WPF应用程序中有这个DataTemplate

当我点击一个按钮时,我需要得到TextBlock Name="titleCategory"并改变它的颜色。

目前我无法选择TextBlock

你能给我一个简单的解决方案吗?

<DataTemplate x:Key="CategoriesSelectedDataTemplate">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Border d:LayoutOverrides="Width, Height"
                CornerRadius="5"
                HorizontalAlignment="Stretch"
                Background="Transparent" >
            <TextBlock Name="titleCategory" TextWrapping="Wrap"
                       Text="{Binding CapitalizedDescription, FallbackValue=Category}"
                       Foreground="Red"
                       />
        </Border>
        <!-- 1L main menu HOVER -->
        <Custom:SurfaceListBox
            d:LayoutOverrides="Width"
            ItemsSource="{Binding Shops}"
            ItemTemplate="{DynamicResource ShopUnselectedSurfaceListDataTemplate}"
            Grid.RowSpan="1"
            Grid.Row="1"
            SelectionChanged="shopListBox_SelectionChanged"
            ItemContainerStyle="{DynamicResource CategoriesSurfaceListBoxItemStyle}"
            SelectionMode="Multiple"/>
    </Grid>
</DataTemplate>

如何在DataTemplate中选择单个TextBlock

我用这个代码解决了

            var elem = (FrameworkElement)sender;
            TextBlock myTextBlock = (TextBlock)elem.FindName("titleCategory");
            myTextBlock.Foreground = System.Windows.Media.Brushes.Yellow;