DataTemplate から ToggleButton を取得しようとしています
ListBoxItem lbi = this.UnitsListBox.ItemContainerGenerator.ContainerFromItem(obj) as ListBoxItem;
lbi は問題ありません (null ではありません)。
私はこれをしたいと思います:
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>