locked
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">
                
                <ListBox.ItemTemplate>
                    <DataTemplate>
    			<Grid x:Name="grdContent" ShowGridLines="False" Margin="0, 15, 0, 0">
    	                        <Grid.RowDefinitions>
    	                           
    	                            
    	                        </Grid.RowDefinitions>
    
    	                        <Grid.ColumnDefinitions>
    	                            <ColumnDefinition Width="50"></ColumnDefinition>
    	                            <ColumnDefinition Width="*"></ColumnDefinition>
    	                        </Grid.ColumnDefinitions>
    
    	                        <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" />
    					</Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

    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!

    Regards

    Echo6

    Friday, March 9, 2012 6:37 AM

Answers

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

    http://windowsphonegeek.com/tips/how-to-access-a-control-placed-inside-listbox-itemtemplate-in-wp7

    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