如何在DataTemplate中选择单个TextBlock

时间:2014-03-16 07:56:55

标签: c# .net wpf wpf-controls

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

1 个答案:

答案 0 :(得分:1)

我用这段代码解决了

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