Dynamische ListBox Controls

Status
Niet open voor verdere reacties.

Sphero

Gebruiker
Lid geworden
17 jun 2009
Berichten
5
Vraagje,

Vanuit C# WPF bouw ik dynamische listbox controls (hiervoor gebruik ik dus geen XAML).
Tijdens het aanmaken van de Listboxen, voeg ik ListBoxItems toe aan het Listboxen.

Naderhand wil ik, als ik op een ListBoxItem click, de text van de ListBoxItem doorsturen en van de ListBox waaronder de ListBoxItem valt.

Hoe kan ik dit doen?

Code tot nu toe:
ListBox iListBox;
ListBoxItem iListBoxItem;

string[] ListBoxes = new string[] {"ListBox1","ListBox2"};
string[] ListBoxItem = new string[] { "ListBoxItem1", "ListBoxItem2", "ListBoxItem3" };

foreach(string box in ListBoxes)
{
iListBox = new ListBox();
iListBox.Name = box;

foreach (string item in ListBoxItem)
{
iListBoxItem = new ListBoxItem();
iListBoxItem.Content = item;
iListBoxItem.Selected += ListBoxItem_Do(box, item);

iListBox.Items.Add(iListBoxItem);

}

LeftPanel.Children.Add(iListBox);
}


// Geeft de melding: Cannot implicitly convert type 'void' to 'System.Windows.RoutedEventHandler’
public void ListBoxItem_Do(string test, string test2)
{
MessageBox.Show(test);
}
 
Laatst bewerkt:
void MakeButton2()
{
Button b2 = new Button();
b2.Click += new RoutedEventHandler(Onb2Click2);
}
void Onb2Click2(object sender, RoutedEventArgs e)
{
//logic to handle the Click event
}

Je zult dus een custom RoutedEventArg moeten maken en hier de data
meegeven (string1 en string2).
 
Code:
   public void Test()
        {
            ListBox lb = new ListBox();
            lb.Items.Add(new ListBoxItem() { Content = "lbi 1" });
            lb.Items.Add(new ListBoxItem() { Content = "lbi 2" });
            lb.Items.Add(new ListBoxItem() { Content = "lbi 3" });
            lb.Items.Add(new ListBoxItem() { Content = "lbi 4" });

            lb.SelectionChanged += new SelectionChangedEventHandler(lb_SelectionChanged);
            grd.Children.Add(lb);
        }

        void lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox != null)
            {
                // naam van de listbox
                string nameOfListbox = listBox.Name;

                // naam van het geselecteerde item
                if (listBox.SelectedItem != null)
                {
                    string text = listBox.SelectedItem.ToString();
                }
            }
        }
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan