How can I data bind a list of strings to a ListBox in WPF/WP7?

后端 未结 4 1626
醉酒成梦
醉酒成梦 2020-11-27 13:42

I am trying to bind a list of string values to a listbox so that their values are listed line by line. Right now I use this:



        
4条回答
  •  失恋的感觉
    2020-11-27 14:20

    If simply put that your ItemsSource is bound like this:

    YourListBox.ItemsSource = new List { "One", "Two", "Three" };
    

    Your XAML should look like:

    
         
             
                 
                     
                 
             
         
     
    

    Update:

    This is a solution when using a DataContext. Following code is the viewmodel you will be passing to the DataContext of the page and the setting of the DataContext:

    public class MyViewModel
    {
        public List Items
        {
            get { return new List { "One", "Two", "Three" }; }
        }
    }
    
    //This can be done in the Loaded event of the page:
    DataContext = new MyViewModel();
    

    Your XAML now looks like this:

    
        
            
                
                    
                
            
        
    
    

    The advantage of this approach is that you can put a lot more properties or complex objects in the MyViewModel class and extract them in the XAML. For example to pass a List of Person objects:

    public class ViewModel
    {
        public List Items
        {
            get
            {
                return new List
                {
                    new Person { Name = "P1", Age = 1 },
                    new Person { Name = "P2", Age = 2 }
                };
            }
        }
    }
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    

    And the XAML:

    
        
            
                
                    
                    
                
            
        
    
    

    Hope this helps! :)

提交回复
热议问题