在WPF中自定义ComboBox

时间:2012-05-16 22:12:07

标签: c# wpf list combobox

我有一份狗和一系列猫的清单。我想在同一个组合框中显示狗和猫的列表。但是我想区分它们。

例如。在我列出狗之前它应该出现一个,让我们把它称为“不可选择的项目”,用不同的字体颜色表示“DOGS”,然后是狗的列表。在狗列表之后,另一个不同字体颜色的“不可选择的项目”应该是“CATS”,然后是猫的列表。

有谁知道怎么做?我一直在寻找并且无法找到能够做到这一点的房产。

2 个答案:

答案 0 :(得分:2)

使用ComboBoxItem作为“标题”条目。例如:

ComboBoxItem CBI = new ComboBoxItem();
CBI.Content = "DOGS";
CBI.IsEnabled = false;
CBI.Background = Brushes.Aqua;
comboBox1.Items.Add(CBI);
//Add dogs here

答案 1 :(得分:1)

我建议创建一个狗和猫都可以实现的界面。然后绑定到这些对象的集合,并使用xaml根据对象的类型更改外观。

public enum AnimalType
{
    Dog,
    Cat
}
public interface Animal
{
    AnimalType animal { get; set; }
    string Name { get; set; }
}

public class Cat : Animal
{
    public AnimalType animal { get; set; }
    public string Name { get; set; }

    public Cat()
    {
        animal = AnimalType.Cat;
    }
}


public class Dog : Animal
{
    public AnimalType animal { get; set; }
    public string Name { get; set; }

    public Dog()
    {
        animal = AnimalType.Dog;
    }
}

public class MyViewModel
{
    public List<Animal> MyAnimals { get; set; }

    public MyViewModel()
    {
        MyAnimals = new List<Animal>();

        var a = new Dog();
        var b = new Cat();

        MyAnimals.Add(a);
        MyAnimals.Add(b);
    }
}

然后在你的XAML绑定到List(或使用observable collection进行自动道具更新)

<ComboBox ItemsSource="{Binding Path=MyAnimals}" Style="{StaticResource MyCombo}">

然后创建一个样式以根据您的数据更改外观。

<Style TargetType="ComboBox" x:Key="MyCombo">
                <Style.Triggers>
                    <DataTrigger Binding="AnimalType" Value="Dog">
                        <Setter Property = "Foreground" Value="Green"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>