programing

WPF의 comboBox에 항목 추가

css3 2023. 4. 15. 09:13

WPF의 comboBox에 항목 추가

WPF 창에 comboBox를 추가한 경우 comboBox에 항목을 추가하려면 어떻게 해야 합니까?설계의 XAML 코드 또는 NameOfWindow.xaml.cs 파일 중 어느 쪽입니까?

케이스 1 - 데이터 소스가 없습니다.

를 입력하기만 하면 됩니다.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. 임의 IEnumerabletype은 데이터 소스로 사용할 수 있습니다.할 수 있습니다.

  1. 을 묶다ItemsSource에 있어서의 재산.XAML데이터 소스로 이행합니다.
<!-- MyDataSource is an IEnumerable type property in ViewModel -->
<ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" />
  1. 데이터 소스를 에 할당하다ItemsSource코드 배후에 있는 속성입니다.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    comboBox1.ItemsSource = new List<string> { "Alice", "Bob", "Charlie" };
}

케이스 3 - 데이터 소스가 있으며 항목이 변경될 수 있습니다.

  1. 를 사용해야 합니다.ObservableCollection<T>데이터 소스로서
  2. 바인드해야 합니다.ItemsSource에 있어서의 재산.XAML(상기와 같이) 데이터 소스에 접속합니다.
  3. 데이터 소스를 에 할당할 수 있습니다.ItemsSource코드 배후에 있는 속성(위 그림 참조)

의 사용방법ObservableCollection<T>데이터 원본에 항목이 추가되거나 데이터 원본에서 제거될 때마다 변경 내용이 UI에 즉시 반영되도록 합니다.데이터 저장 방법에 대한 책임은 사용자에게 있습니다.ObservableCollection<T>.

Observable Collection을 구축하여 활용하는 것이 좋습니다.

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

cbx는 comobox 이름입니다.

리스트, 관찰 가능한 수집 INotify의 차이도 확인.속성 변경

이것을 사용하다

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

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

또는

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

myComboBox.SelectedIndex = 0;      

이 값은 XAML 또는 .cs에서 입력할 수 있습니다.컨트롤을 데이터로 채우는 방법은 몇 가지 있습니다.WPF 테크놀로지에 대해 자세히 읽어보시는 것이 좋습니다.WPF 테크놀로지는 필요에 따라 다양한 방법으로 작업을 수행할 수 있습니다.프로젝트 요구에 따라 방법을 선택하는 것이 더 중요합니다.여기서부터 시작하세요.콤보박스를 생성하여 데이터를 채우는 간단한 기사입니다.

생각합니다comboBox1.Items.Add("X");추가하다stringComboBox로, 대신ComboBoxItem.

적절한 해결책은

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

이 작업을 수행하는 방법은 여러 가지가 있습니다.다음은 간단한 예입니다.

<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을 사용하는 것이 가장 좋습니다.

OleDBC Connection을 사용하여 -> 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();

이상입니다:)

언급URL : https://stackoverflow.com/questions/11878217/add-items-to-combobox-in-wpf