【问题标题】:how to access elements in a StackPanel in listbox如何访问列表框中 StackPanel 中的元素
【发布时间】:2013-05-13 07:15:28
【问题描述】:

我有一个ListBox,其中包含一个StackPanel,其中包含一个Image 和一个TextBlock。我想通过 c#(代码隐藏)访问 TextBlock 以手动更改它的字体。

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

我需要访问所有单元格的“catName”TextBlock

【问题讨论】:

    标签: c# xaml listbox windows-phone-8 stackpanel


    【解决方案1】:

    试试这个--->

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

    你可以这样使用上面的方法--->

    ListBoxItem item = this.list.ItemContainerGenerator.ContainerFromIndex(2) as ListBoxItem;
    TextBlock txt = FindFirstElementInVisualTree<TextBlock>(item);
    txt.Text = "some text";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2021-09-14
      • 2012-05-23
      • 2022-10-04
      相关资源
      最近更新 更多