仅在组合框 C# 中显示某些类型的元素

Only show elements of certain types in combobox c#

我有一个 WPF 应用程序,我有多个组合框,我希望它们中的每一个都采用相同的列表,然后让它们中的每一个都采用列表中的特定类型。

我想要的示例:

我有:

当前 XAML :

            <ComboBox Grid.Column="1" Grid.Row="2" ItemsSource="{Binding Composants}"/> 
            <ComboBox Grid.Column="1" Grid.Row="4"/>
            <ComboBox Grid.Column="1" Grid.Row="6"/>
            <ComboBox Grid.Column="3" Grid.Row="2"/>
            <ComboBox Grid.Column="3" Grid.Row="4"/>
            <ComboBox Grid.Column="3" Grid.Row="6"/>
            <TextBlock  Grid.Column="1" Grid.Row="1" Text="Moteur :" TextWrapping="Wrap" VerticalAlignment="Bottom"/>
            <TextBlock  Grid.Column="1" Grid.Row="3" Text="Suspensions :" TextWrapping="Wrap" VerticalAlignment="Bottom"/>
            <TextBlock  Grid.Column="1" Grid.Row="5" Text="Freins :" TextWrapping="Wrap" VerticalAlignment="Bottom"/>
            <TextBlock  Grid.Column="3" Grid.Row="1" Text="Pneus :" TextWrapping="Wrap" VerticalAlignment="Bottom"/>
            <TextBlock  Grid.Column="3" Grid.Row="3" Text="Transmission :" TextWrapping="Wrap" VerticalAlignment="Bottom"/>
            <TextBlock  Grid.Column="3" Grid.Row="5" Text="Turbo :" TextWrapping="Wrap" VerticalAlignment="Bottom"/>

c#,从存根加载的列表:

        List<Composant> composants = new List<Composant>()
    {
                new Moteur("Moteur de base", 0, 1, 1),
                new Moteur("Moteur de course", 50000, 1.6, 1.2),
                new Moteur("Moteur de compétition", 100000, 1.9, 1.76),

                new Turbo("Turbo de base" , 0, 1, 1),
                new Turbo("Turbo de course", 50000, 1.6, 1.2),
                new Turbo("Turbo de compétition" , 100000, 1.54, 1.76),

                new Suspension("Suspensions de base", 0, 1),
                new Suspension("Suspensions de course", 50000, 1.6),
                new Suspension("Suspensions de compétition", 100000, 1.85),

                new Frein("Freins de base", 0, 1),
                new Frein("Freins de course", 50000, 1.6),
                new Frein("Freins de compétition",  100000, 1.85),

                new Pneus("Pneus de base", 0, 1,1,1),
                new Pneus("Pneus de course", 50000, 1.6,1.5,1.1),
                new Pneus("Pneus de compétition", 100000, 1.85,1.55,1.2)
    };

我认为您可以通过检查 composant 的类型来填充列表(假定 MoteurTurbo、...所有派生自 类 Composant).

foreach (var item in composants)
{
    if (item is Moteur)
    {
        moteurComboBox.Items.Add(item);
    }
    else if (item is Turbo)
    {
        turboComboBox.Items.Add(item);
    }
    else ...
}