2012-08-09 58 views
15

Cuando agregué un comboBox a la ventana de WPF, ¿cómo agrego elementos al comboBox? Int el código XAML para el diseño o en el archivo NameOfWindow.xaml.cs?Agregar elementos a comboBox en WPF

+0

WPF tiene una gran característica para eso. Se llama "Databinding". Para comenzar con WPF [esto] (http://joshsmithonwpf.wordpress.com/a-guided-tour-of-wpf/) debería ayudarlo. – Andre

+1

ahem .. WinForms también tenía enlaces de datos :) – LadderLogic

+1

No menciono lo contrario. Acabo de decir que WPFs Databinding es una gran característica :) – Andre

Respuesta

6

Utilice esta

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

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

O

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

myComboBox.SelectedIndex = 0;  
+1

¡Está bien, funciona bien! Pero si quiero un nombre o un titular para el cuadro desplegable como "Tus opciones:", entonces supongo que solo agrego eso primero en el conjunto, pero cuando se hace una selección, lo verifico para que el índice 0 no esté activado? ¿O hay un mejor camino? –

+0

Sí Esto es bueno. –

+0

No, obtengo "sus opciones" dos veces? Está en el "botón" pero también está en la lista que aparece cuando hago clic en el cuadro combinado. –

4

Usted puede llenarlo de XAML o de Cs. Hay pocas formas de llenar los controles con datos. Lo mejor para usted es que lea más sobre la tecnología WPF, le permite hacer muchas cosas de muchas maneras, según sus necesidades. Es más importante elegir un método basado en las necesidades de su proyecto. Puede comenzar here. Es un artículo fácil sobre crear combobox y llenarlo con algunos datos.

26

Escenario 1 - usted no tiene una fuente de datos para los elementos del ComboBox
Puede completar el ComboBox con valores estáticos de la siguiente manera -
De XAML:

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

O, desde CodeBehind:

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

2.a Escenario - que tienen un origen de datos y los artículos nunca cambiarnos
Usted puede use la fuente de datos para poblar el ComboBox. Cualquier tipoIEnumerable se puede utilizar como fuente de datos. Debe asignarlo a la propiedad ItemsSource de ComboBox y le irá bien (depende de usted cómo llene el IEnumerable).

Escenario 2.b - que tiene una fuente de datos, y los artículos mismo puede cambiar
Usted debe utilizar un ObservableCollection<T> como la fuente de datos y asignarlo a la propiedad ItemsSource del ComboBox (es depende de ti cómo llenas el ObservableCollection<T>). El uso de un ObservableCollection<T> garantiza que cada vez que se agregue o elimine un elemento de la fuente de datos, el cambio se reflejará inmediatamente en la UI.

0

Hay muchas maneras de realizar esta tarea. Aquí es simple:

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

A continuación, tenemos el código 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); 
    } 

Nota: Este es el uso de la reflexión. Si desea obtener más información sobre los conceptos básicos de la reflexión y por eso es posible que desee utilizarlo, esto es un gran artículo de introducción:

Si desea aprender más información sobre cómo es posible utilizar la reflexión con WPF en concreto, he aquí algunos recursos:

Y si quieres masivamente acelerar el rendimiento de la reflexión, lo mejor es utilizar la IL hacer eso, así:

-1

Creo que comboBox1.Items.Add("X"); agregará string a ComboBox, en lugar de ComboBoxItem.

La solución correcta es

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

Con OLEDBConnection -> conectar a 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(); 

Eso es todo :)