简体   繁体   中英

How to select a single TextBlock in a DataTemplate

I have this DataTemplate in my WPF application.

When I click a button I need to get TextBlock Name="titleCategory" and change its color.

At the moment I am not able to select the TextBlock .

Could you provide me a simple solution?

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

I solved with this code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM