Question

I have a ListBox that contains a StackPanel which contains an Image and a TextBlock. I want to access the TextBlock via c# (code-behind) to change it's font manually.

Relevent XAML:

<ListBox x:Name="CategoriesListBox" Margin="0,0,-12,0" ItemsSource="{Binding Categories}" SelectionChanged="CategoriesListBox_SelectionChanged" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17" Width="432" Height="62">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="40"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Image x:Name="catImage" Source="{Binding icon}"/>
                            <TextBlock x:Name="catName"  Grid.Column="1" Text="{Binding name_shown}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}"/>
                        </Grid>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I need to access the "catName" TextBlock for all cells.

Was it helpful?

Solution

try this--->

private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
    var count = VisualTreeHelper.GetChildrenCount(parentElement);
    if (count == 0)
        return null;

    for (int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(parentElement, i);

        if (child != null && child is T)
        {
            return (T)child;
        }
        else
        {
            var result = FindFirstElementInVisualTree<T>(child); 
            if (result != null)
                return result;

        }
    }
    return null;
}

u can use above method in this way--->

ListBoxItem item = this.list.ItemContainerGenerator.ContainerFromIndex(2) as ListBoxItem;
TextBlock txt = FindFirstElementInVisualTree<TextBlock>(item);
txt.Text = "some text";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top