May 7

admin

WPF ListBox

wpf

The ListBox control in WPF allows you to display a list of items to the user. The user can then select one item or multiple items as needed.

Below you can find an example with XAML markup:


    
        
            Red
            Green
            Blue
        
    


Getting selected items

To the get the selected item in the ListBox you can use the SelectedItem property to get a single item or the SelectedItems property to get multiple items.

Below you can find an example for getting selected items:


    
        
        
            
                
                    
                
            
        
    


namespace WpfApplication8
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List colors = new List();
            colors.Add(new MyColor("Red"));
            colors.Add(new MyColor("Green"));
            colors.Add(new MyColor("Blue"));

            ListBoxTest.ItemsSource = colors;

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            foreach (MyColor item in ListBoxTest.SelectedItems)
            {
                MessageBox.Show(item.Name);
            }

        }


    }
    public class MyColor
    {
        public string Name { get; set; }

        public MyColor(string n)
        {
            this.Name = n;
        }
    }
   
}

No Comments

Add Comment