在WPF中将项添加到comboBox

时间:2012-08-09 06:55:47

标签: c# wpf

当我将一个comboBox添加到WPF窗口时,如何将项目添加到comboBox?在设计的XAML代码中或在NameOfWindow.xaml.cs文件中?

7 个答案:

答案 0 :(得分:41)

场景1 - 您没有ComboBox项目的数据源
您可以使用静态值填充ComboBox,如下所示 -
来自XAML:

<ComboBox Height="23" Name="comboBox1" Width="120">
        <ComboBoxItem Content="X"/>
        <ComboBoxItem Content="Y"/>
        <ComboBoxItem Content="Z"/>
</ComboBox>  

或者,来自CodeBehind:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.Items.Add("X");
    comboBox1.Items.Add("Y");
    comboBox1.Items.Add("Z");
}  

场景2.a - 您有数据源,项目永远不会更改
可以使用数据源来填充ComboBox。 任何 IEnumerable类型都可以用作数据源。你需要将它分配给ComboBox的ItemsSource属性,并且这样做会很好(由你来填充IEnumerable)。

场景2.b - 您有数据源,项目可能会更改
使用ObservableCollection<T>作为数据源,并将其分配给ComboBox的ItemsSource属性(由您自己填充ObservableCollection<T>的方式) 。使用ObservableCollection<T>可确保无论何时在数据源中添加或删除项目,更改都会立即反映在UI上。

答案 1 :(得分:31)

最好建立ObservableCollection并利用它

public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;

cbx是comobobox名称

另请阅读:Difference between List, ObservableCollection and INotifyPropertyChanged

答案 2 :(得分:9)

使用此

string[] str = new string[] {"Foo", "Bar"};

myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;

OR

foreach (string s in str)
    myComboBox.Items.Add(s);

myComboBox.SelectedIndex = 0;      

答案 3 :(得分:4)

您可以从XAML或.cs填写。用数据填充控件的方法很少。您最好阅读有关WPF技术的更多信息,它可以根据您的需求以多种方式执行许多操作。根据您的项目需求选择方法更为重要。你可以开始here。这是一篇关于创建组合框并用一些数据填充它的简单文章。

答案 4 :(得分:0)

执行此任务的方法有很多种。这是一个简单的:

<Window x:Class="WPF_Demo1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     x:Name="TestWindow"
    Title="MainWindow" Height="500" Width="773">

<DockPanel LastChildFill="False">
    <StackPanel DockPanel.Dock="Top" Background="Red" Margin="2">
        <StackPanel Orientation="Horizontal" x:Name="spTopNav">
            <ComboBox x:Name="cboBox1" MinWidth="120"> <!-- Notice we have used x:Name to identify the object that we want to operate upon.-->
            <!--
                <ComboBoxItem Content="X"/>
                <ComboBoxItem Content="Y"/>
                <ComboBoxItem Content="Z"/>
            -->
            </ComboBox>
        </StackPanel>
    </StackPanel>
    <StackPanel DockPanel.Dock="Bottom" Background="Orange" Margin="2">
        <StackPanel Orientation="Horizontal" x:Name="spBottomNav">
        </StackPanel>
        <TextBlock Height="30" Foreground="White">Left Docked StackPanel 2</TextBlock>
    </StackPanel>
    <StackPanel MinWidth="200" DockPanel.Dock="Left" Background="Teal" Margin="2" x:Name="StackPanelLeft">
        <TextBlock  Foreground="White">Bottom Docked StackPanel Left</TextBlock>

    </StackPanel>
    <StackPanel DockPanel.Dock="Right" Background="Yellow" MinWidth="150" Margin="2" x:Name="StackPanelRight"></StackPanel>
    <Button Content="Button" Height="410" VerticalAlignment="Top" Width="75" x:Name="myButton" Click="myButton_Click"/>


</DockPanel>

</Window>      

接下来,我们有C#代码:

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        ComboBoxItem cboBoxItem = new ComboBoxItem(); // Create example instance of our desired type.
        Type type1 = cboBoxItem.GetType();
        object cboBoxItemInstance = Activator.CreateInstance(type1); // Construct an instance of that type.
        List<string> myStrings = new List<string>(); // Fill a list with useful strings.
        for (int i = 0; i < 12; i++)
        {
            string newName = "stringExample" + i.ToString();
            myStrings.Add(newName);
        }
        foreach (string str in myStrings) // Generate the objects from our list of strings.
        {
            ComboBoxItem item = this.CreateComboBoxItem((ComboBoxItem)cboBoxItemInstance, "nameExample_" + str, str);
            cboBox1.Items.Add(item); // Add each newly constructed item to our NAMED combobox.
        }
    }
    private ComboBoxItem CreateComboBoxItem(ComboBoxItem myCbo, string content, string name)
    {
        Type type1 = myCbo.GetType();
        ComboBoxItem instance = (ComboBoxItem)Activator.CreateInstance(type1);
        // Here, we're using reflection to get and set the properties of the type.
        PropertyInfo Content = instance.GetType().GetProperty("Content", BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo Name = instance.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
        this.SetProperty<ComboBoxItem, String>(Content, instance, content);
        this.SetProperty<ComboBoxItem, String>(Name, instance, name);

        return instance;
        //PropertyInfo prop = type.GetProperties(rb1);
    }

注意:这是使用反射。 如果您想了解更多关于反思的基础知识以及为什么要使用它,这是一篇很棒的介绍性文章:

如果您想了解更多关于如何的信息,您可以专门使用WPF反射,这里有一些资源:

如果你想大量加速反射的性能,最好使用IL来做到这一点,如下所示:

答案 5 :(得分:-1)

我认为comboBox1.Items.Add("X");会将string添加到ComboBox,而不是ComboBoxItem

正确的解决方案是

ComboBoxItem item = new ComboBoxItem();
item.Content = "A";
comboBox1.Items.Add(item);

答案 6 :(得分:-1)

使用OleDBConnection - &gt;连接到Oracle

OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "Provider=MSDAORA;Data Source=oracle;Persist Security Info=True;User ID=system;Password=**********;Unicode=True";

            OleDbCommand comd1 = new OleDbCommand("select name from table", con);
            OleDbDataReader DR = comd1.ExecuteReader();
            while (DR.Read())
            {
                comboBox_delete.Items.Add(DR[0]);
            }
            con.Close();

这就是全部:)

相关问题