在WPF中向comboBox添加项目

43

当我在WPF窗口中添加了一个comboBox,如何向其中添加项?是在设计的XAML代码中还是在NameOfWindow.xaml.cs文件中进行操作?


WPF有一个非常棒的功能,叫做“数据绑定”。如果想要开始学习WPF,可以参考这个链接:http://joshsmithonwpf.wordpress.com/a-guided-tour-of-wpf/。 - Andre
1
啊咳.. WinForms 也有数据绑定 :) - LadderLogic
3
我没有提及相反的意思。我只是说WPF的数据绑定是一个很棒的功能 :) - Andre
7个回答

74

情况一 - 没有数据源:

您可以按照以下方式使用静态值填充ComboBox -

  1. 从XAML中:
<ComboBox Height="23" Name="comboBox1" Width="120">
    <ComboBoxItem Content="Alice"/>
    <ComboBoxItem Content="Bob"/>
    <ComboBoxItem Content="Charlie"/>
</ComboBox>
  1. 来自CodeBehind - 1:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.Items.Add("Alice");
    comboBox1.Items.Add("Bob");
    comboBox1.Items.Add("Charlie");
}
  1. 从 CodeBehind - 2:
// insert item at specified index of populated ComboBox
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.Items.Insert(2, "Alice");
    comboBox1.Items.Insert(5, "Bob");
    comboBox1.Items.Insert(8, "Charlie");
}

情况2 - 您有一个数据源,且项目永远不会更改:

您可以使用数据源来填充ComboBox任何IEnumerable类型都可以用作数据源。您可以 -

  1. XAML中的ItemsSource属性绑定到数据源,例如 -
<!-- MyDataSource is an IEnumerable type property in ViewModel -->
<ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" />
  1. 在代码后台将 data-source 赋值给 ItemsSource 属性,例如 -
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.ItemsSource = new List<string> { "Alice", "Bob", "Charlie" };
}

CASE 3 - 数据源可能会发生改变

  1. 应该使用ObservableCollection<T>作为数据源
  2. 应该XAML中将ItemsSource属性绑定到数据源(如上所示)
  3. 可以在代码后台将数据源分配给ItemsSource属性(如上所示)

使用ObservableCollection<T>确保每当向数据源添加或删除项目时,更改将立即反映在UI上。您可以自己决定如何填充ObservableCollection<T>


41

11

使用此代码

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

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

或者

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

myComboBox.SelectedIndex = 0;      

1
很好,它运行得很好!但是如果我想要像“您的选项:”这样的名称或标题用于组合框,那么我猜我只需首先将其添加到数组中,但是当进行选择时,我会检查索引0是否被激活!?还是有更好的方法吗? - 3D-kreativ
不,我得到了“你的选项”两次!?它在“按钮”上,但当我点击组合框时,它也在下拉列表中。 - 3D-kreativ
有没有办法解决这个问题?我想在按钮上放一个名称,当我按下按钮时,我希望下拉的是项目,而不是按钮的名称。如果可以做到这一点,将不胜感激! - 3D-kreativ

4
您可以从XAML或.cs中填充它。有几种方法可以填充控件的数据。最好您了解更多关于WPF技术的知识,因为它允许以多种方式执行许多操作,具体取决于您的需求。选择方法基于您的项目需求更为重要。您可以从这里开始。这是一篇简单的文章,介绍了如何创建组合框并用一些数据填充它。

0

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

正确的解决方案是

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

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.
        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);
    }

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

如果您想了解如何在WPF中使用反射,这里有一些资源:

如果您想大幅度提高反射的性能,最好使用IL来实现,像这样:


-1

使用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();

就这些了 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接