我想从一个DataTemplate让我的切换按钮为什么VisualTreeHelper.GetChildrenCount(lbi)== 0?
ListBoxItem lbi = this.UnitsListBox.ItemContainerGenerator.ContainerFromItem(obj) as ListBoxItem;
LBI是确定(不为空)。
我想做到这一点:
ContentPresenter cp = VisualTreeHelper.GetChild(lbi, 0) as ContentPresenter;
ToggleButton btn = (ToggleButton) VisualTreeHelper.GetChild(cp, 0);
但
VisualTreeHelper.GetChildrenCount(lbi) is 0.
这是我的XAML
<ListBox MaxWidth="215" FlowDirection="RightToLeft" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" DockPanel.Dock="Left" Name="UnitsListBox" VirtualizingStackPanel.IsVirtualizing="False" SelectionChanged="UnitsListBox_SelectionChanged" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Resources>
<Style TargetType="Button"/>
</ListBox.Resources>
<ListBox.ItemTemplate >
<DataTemplate >
<ToggleButton x:Name="UnitSidebarButton" FlowDirection="LeftToRight" Height="60" Width="60" HorizontalContentAlignment="Center" Background="Transparent" Margin="0" Padding="0" Checked="UnitSidebarButton_Checked" Unchecked="UnitSidebarButton_Unchecked" Focusable="False" VirtualizingStackPanel.IsVirtualizing="False">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Converter={StaticResource cIMSidebarConverter2}}" TextWrapping="Wrap" TextAlignment="Center" Background="Transparent"/>
</Grid>
</ToggleButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您是否确定在运行代码之前生成了容器? – Rachel 2012-04-16 14:59:48
@Rachel我认为它们是保证生成的,因为lbi不为空。 – 0x4f3759df 2012-04-16 15:01:33