我正在尝试从 DataTemplate 获取我的 ToggleButton
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>