Programmatically binding List to ListBox

后端 未结 4 558
说谎
说谎 2020-12-09 09:25

Let\'s say, for instance, I have the following extremely simple window:



        
4条回答
  •  隐瞒了意图╮
    2020-12-09 09:28

    If the data list is created in code then you're going to have to bind it in code, like so:

    eventList.ItemsSource = ListOfNames;
    

    Now binding to a list of strings is a very simple example. Let's take a more complex one.

    Say you have a person class:

    public class Person {
        public string FirstName { get; set; }
        public string Surname { get; set; }
    }
    

    To display a list of persons you could bind a list to the ListBox, but you'll end up with a listbox that displays "Person" for each entry, because you haven't told WPF how to display a person object.

    To tell WPF how to visually display data objects we define a DataTemplate like so:

    
        
            
                
                
                
            
        
    
    
        
    
    
    public Window1() {
        InitializeComponent();
        List people = new List();
        people.Add(new Person() { FirstName = "Cameron", Surname = "MacFarland" });
        people.Add(new Person() { FirstName = "Bea", Surname = "Stollnitz" });
        people.Add(new Person() { FirstName = "Jason", Surname = "Miesionczek" });
        listBox.ItemsSource = people;
    }
    

    This will nicely display "Firstname Surname" in the list.

    If you wanted to change the look to be say "Surname, Firstname" all you need to do is change the XAML to:

    
        
        
        
    
    

提交回复
热议问题