wpf 虚拟树获取listbox的usercontrol

<Window x:Class="WpfExpand.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfExpand"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel Orientation="Horizontal">
            <ListBox x:Name="d2" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Name="p1" Margin="10" DockPanel.Dock="Right">
                            <TextBlock Text="{Binding Name}" FontWeight="Bold" FontSize="18" />
                            <TextBlock Text="{Binding age}" Margin="0,4,0,0" FontSize="14"
                               Foreground="#c6de96" TextWrapping="WrapWithOverflow" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </StackPanel>
        
    </Grid>
</Window>

this.Dispatcher.InvokeAsync(new Action(delegate
            {

                ListBoxItem myListBoxItem = (ListBoxItem)(d2.ItemContainerGenerator.ContainerFromIndex(0));
                ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
                DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
                StackPanel target = (StackPanel)myDataTemplate.FindName("p1", myContentPresenter);
            }));

FindVisualChild方法


        private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
上一篇:【WPF】实现Winform中ListView效果(ListBox横向排列)


下一篇:列表框 listbox