C# 在 WPF 中将项目添加到组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11878217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:36:54  来源:igfitidea点击:

Add items to comboBox in WPF

c#wpf

提问by 3D-kreativ

When I have added a comboBox to the WPF window, how do I add items to the comboBox? Int the XAML code for the design or in NameOfWindow.xaml.cs file?

当我将组合框添加到 WPF 窗口时,如何向组合框添加项目?设计或 NameOfWindow.xaml.cs 文件中的 XAML 代码?

回答by Nikhil Agrawal

Use this

用这个

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;      

回答by Varius

You can fill it from XAML or from .cs. There are few ways to fill controls with data. It would be best for You to read more about WPF technology, it allows to do many things in many ways, depending on Your needs. It's more important to choose method based on Your project needs. You can start here. It's an easy article about creating combobox, and filling it with some data.

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

回答by Pranay Rana

Its better to build ObservableCollectionand take advantage of it

最好构建ObservableCollection并利用它

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

cbx is comobobox name

cbx 是组合框名称

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

另请阅读:List、ObservableCollection 和 INotifyPropertyChanged 之间的区别

回答by atiyar

Scenario 1 - you don't have a data-source for the items of the ComboBox
You can just populate the ComboBox with static values as follows -
From XAML:

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

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

Or, from CodeBehind:

或者,来自 CodeBehind:

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

Scenario 2.a - you have a data-source, and the items never get changed
You canuse the data-source to populate the ComboBox. AnyIEnumerabletype can be used as the data-source. You need to assign it to the ItemsSourceproperty of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable).

场景 2.a - 您有一个数据源,并且项目永远不会改变
可以使用数据源来填充 ComboBox。任何IEnumerable类型都可以用作数据源。您需要将它分配给ItemsSourceComboBox的属性,这样就可以了(这取决于您如何填充IEnumerable)。

Scenario 2.b - you have a data-source, and the items might get changed
You shoulduse an ObservableCollection<T>as the data-source and assign it to the ItemsSourceproperty of the ComboBox (it's up to you how you populate the ObservableCollection<T>). Using an ObservableCollection<T>ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI.

场景 2.b - 您有一个数据源,并且项目可能会更改
应该使用 anObservableCollection<T>作为数据源并将其分配给ItemsSourceComboBox的属性(这取决于您如何填充ObservableCollection<T>)。使用 可ObservableCollection<T>确保每当向数据源添加或删除项目时,更改将立即反映在 UI 上。

回答by devinbost

There are many ways to perform this task. Here is a simple one:

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

<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>      

Next, we have the C# code:

接下来,我们有 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.
        for (int i = 0; i < 12; i++)
        {
            string newName = "stringExample" + i.ToString();
           // Generate the objects from our list of strings.
            ComboBoxItem item = this.CreateComboBoxItem((ComboBoxItem)cboBoxItemInstance, "nameExample_" + newName, newName);
            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);
    }

Note: This is using reflection. If you'd like to learn more about the basics of reflection and why you might want to use it, this is a great introductory article:

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

If you'd like to learn more about howyou might use reflection with WPF specifically, here are some resources:

如果您想详细了解如何专门将反射与 WPF 结合使用,请参阅以下资源:

And if you want to massivelyspeed up the performance of reflection, it's best to use IL to do that, like this:

如果你想大幅提高反射的性能,最好使用 IL 来做到这一点,就像这样:

回答by jiasli

I think comboBox1.Items.Add("X");will add stringto ComboBox, instead of ComboBoxItem.

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

The right solution is

正确的解决办法是

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

回答by starko

With OleDBConnection -> connect to Oracle

使用 OleDBConnection -> 连接到 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();

That's all :)

就这样 :)