我有以下 C# 代码来查找 DependendencyObject 的子项:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) where T : DependencyObject
{
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
foreach (var other in FindVisualChildren<T>(child))
yield return other;
}
else
{
yield return (T)child;
}
}
}
当我遍历底部发布的 XAML 中的 TabItems 时,将每个 TabItem 传递给上述方法,要求它查找所有扩展程序,它什么也不返回。此外,我在附加到每个选项卡项的 Loaded 事件的事件处理程序中发出此请求。
<TextBlock Text="Number of Parts" Grid.Column="0"/>
<ComboBox Grid.Column="2"
Margin="0,0,0,2"
/>
</Grid>
</Expander>
<Expander Header="Date/Time Format"
Margin="5,0,5,0"
Padding="3,3,0,0"
IsExpanded="True" >
<Grid Margin="20,4,0,4">
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Date/Time Format" Grid.Row="0"/>
<ComboBox Name="cmbDateTimeFormats"
Grid.Row="0" Grid.Column="2"/>
</Grid>
</Expander>
</StackPanel>
</DockPanel>
</Border>
</TabItem>
<TabItem Header="Profile">
<Border >
<DockPanel LastChildFill="False">
<StackPanel DockPanel.Dock="Top">
<GroupBox Header="Local"
Margin="5,8" Padding="3,3,0,0"
>
<Grid Margin="20,4,0,4">
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Content="Location..." Grid.Row="0" Name="btnProfLoc" />
<TextBlock Text="{Binding ProfileLocation}" Grid.Row="0" Grid.Column="2"/>
<Button Name="btnSaveProfile" Height="25"
Margin="2,5,0,0" Grid.Row="1"
Padding="2,1" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Save" Margin="5,0"/>
</StackPanel>
</Button>
<Button Name="btnLoadProfile" Height="25"
Margin="2,5,0,0" Grid.Row="2"
Padding="2,1" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Load" Margin="5,0"/>
</StackPanel>
</Button>
<Button Name="btnResetProfile" Height="25"
Margin="2,5,0,0" Grid.Row="3"
Padding="2,1" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Reset" Margin="5,0"/>
</StackPanel>
</Button>
</Grid>
</GroupBox>
</StackPanel>
<StackPanel
DockPanel.Dock="Bottom" Orientation="Horizontal">
</StackPanel>
</DockPanel>
</Border>
</TabItem>
</TabControl>
有人猜我的方法有什么问题吗?我没有在这个特定的自定义控件中尝试过,但是这个方法已被用于在另一个自定义控件中查找给定类型的子项。主要区别在于我要查找的项目是 TabItems 的子项。