How to fill the ListBox correctly so that you can adequately retrieve its items.

For example, if you add elements in this way (which I will describe below), they cannot be adequately extracted, I mean the name of the item. In the case that I wrote below, with the selectitem property, it records not what is needed, but only the name of the item is needed.

<ListBox Name="lb1" > <TextBlock>xxx</TextBlock> <TextBlock>zzz</TextBlock> </ListBox> 
  • 2
    The correct way is not to interfere with a bunch of data and their display. To give a more detailed answer you need to know a little more details about what you want to do. - user227049

5 answers 5

Fill in the ItemsSource property.

I consider the correct use of the pattern-mvvm. 1. Set the DataContext property to: * ListBox * Container ListBox or any other container, which includes the desired ListBox. 2. In Xaml, set the binding (Binding): {Binding} or {Binding Name}

Note: You can use a simple array, then you must implement the INotifyPropertyChanged interface. If you do this, then there is! = 0 the probability that it does not always work. I recommend using ObservableCollection. With him, such problems will not arise. The visual component is edited using styles.

  • If I do this, I can’t delete the listBox.Items.RemoveAt () elements: - test19
  • 3
    @ SOFL, and you delete from the fact that assigned ItemSource. - Gardes

Very simple, you need to import a namespace for system types.

 xmlns:System="clr-namespace:System;assembly=mscorlib" 

and then in the markup, you can fill the ListBox with regular lines

 <ListBox> <System:String>Первый</System:String> <System:String>Второй</System:String> <System:String>Третий</System:String> <System:String>Четвертый</System:String> </ListBox> 

The selected line will be the SelectedItem.

    It is possible so:

     List<string> strings = new List<string> {"xxx", "yyy", "zzz"}; lb1.ItemsSource = strings; 

    And if you need to remove any element, then:

     // Удалить "yyy" strings.Remove("yyy"); 
    • four
      This option will not work;) - user227049

    I filled in this way.

      ArrayList mylist; public static ArrayList listboxload() { ArrayList list = new ArrayList(); list.Add("1as"); list.Add("2ds"); list.Add("3ds"); return list; } 
    • one
      This is not an answer to your question, right? - user227049
     (lb1.Items[0] as TextBlock).Text = "xxx1"; (lb1.Items[1] as TextBlock).Text = "zzz1"; 

    Try it like this. It works for me = /