How can I get the DataTemplate-Controls of each ListBoxItem? RRS feed

  • Question

  • Hello!

    I have a ListBox with a DataTemplate. In the DataTemplate is a grid with a checkbox and a Textblock Control. Now I would like to, that when I click on a button the TextBlock color change to red for the first and the third item for e.g.!

    Here is my Listbox-XAML:

    <ListBox x:Name="lstAntworten" Margin="10,10,0,55" Grid.Row="1" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemContainerStyle="{StaticResource ListBox_NoSelectionColor}" OpacityMask="#FFFEFEFE" Background="Transparent" Width="500" HorizontalAlignment="Left" d:LayoutOverrides="Width">
    			<Grid x:Name="grdContent" ShowGridLines="False" Margin="0, 15, 0, 0">
    	                            <ColumnDefinition Width="50"></ColumnDefinition>
    	                            <ColumnDefinition Width="*"></ColumnDefinition>
    	                        <CheckBox Tag="{Binding Path=ID}" IsChecked="{Binding Status, Mode=TwoWay}" x:Name="chkStatus" Grid.Column="0" Margin="15, 0, 20, 0" HorizontalAlignment="Center" VerticalAlignment="Top" />
    	                        <TextBlock x:Name="txtbText" Text="{Binding Text}" FontSize="18" Margin="15, 0, 15, -5" Grid.Column="1" MouseLeftButtonUp="txtbText_MouseLeftButtonUp" />

    My question is now, how can I get the single ListBoxItems through the Button-Click, so that I can get the Textblock-Control of each ListboxItem?

    Thank you in advance for your answers!



    Friday, March 9, 2012 6:37 AM


  • Hi Echo6,

    First of all, you can use  [ListBoxName].ItemContainerGenerator.ContainerFromIndex(index); to get a ListBoxItem using index.

    After that, you can use VisualTreeHelper to find the TextBlock type element of ListBoxItem.

    Below is a detailed blog with sample code,


    By the way, TextBlock can only change its Foreground property. If you want to change its background color, you can use TextBox instead and set its Is ReadOnly = True.


    Best Regards,


    Monday, March 12, 2012 2:16 AM