WPF FAQ - ListBox

Find answers for the most frequently asked questions
Expand All Collapse All

First create a custom DataTemplate that uses adjacent TextBlocks to render values from 2 different columns next to each other.


<Window.Resources>  
            <DataTemplate x:Key='lbItemsTemplate'>   
                <StackPanel FlowDirection='LeftToRight'  Orientation='Horizontal'>   
                    <TextBlock Text='{Binding Path=Title}'></TextBlock>  
                    <TextBlock Text=' \ '></TextBlock>  
                    <TextBlock Text='{Binding Path=Summary}'></TextBlock>  
                </StackPanel>  
            </DataTemplate>  
</Window.Resources>  

Above, Title and Summary are the two columns.

Then specify this template in your ListBox:


<ListBox x:Name='ListView1' ItemTemplate='{StaticResource lbItemsTemplate}' ItemsSource='{StaticResource InventoryData}'>   
</ListBox>  
Permalink

Items can be displayed horizontally using the ItemsPanel property of the ListBox.

The following lines of code are used to display the items horizontally.

[XAML]

<ListBox Height='40' Width='50'>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
            	<StackPanel Orientation='Horizontal'/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
      <ListBoxItem>1 ITEM 1</ListBoxItem>
<ListBoxItem>2 ITEM 2</ListBoxItem>
<ListBoxItem>3 ITEM 3</ListBoxItem>
</ListBox>
Permalink

You can do this easily by extending the ApplicationCommands.Copy command as follows:

See this forum for better formatting of the code ListView Copy to clipboard selected row.

[XAML]
<ListBox x:Name='myListBox' SelectionMode='Multiple'>   
    <ListBox.Items>  
        <ListBoxItem>Item1</ListBoxItem>  
        <ListBoxItem>Item2</ListBoxItem>  
        <ListBoxItem>Item3</ListBoxItem>  
        <ListBoxItem>Item4</ListBoxItem>  
    </ListBox.Items>  
</ListBox>  

In your code behind:

[C#]
        public Window1()     
        {     
            this.InitializeComponent();   
  
            CommandBinding cb = new CommandBinding(ApplicationCommands.Copy, CopyCmdExecuted, CopyCmdCanExecute);   
  
            this.myListBox.CommandBindings.Add(cb);   
        }   
        void CopyCmdExecuted(object target, ExecutedRoutedEventArgs e)   
        {   
            ListBox lb = e.OriginalSource as ListBox;   
            string copyContent = String.Empty;   
            // The SelectedItems could be ListBoxItem instances or data bound objects depending on how you populate the ListBox.   
            foreach (ListBoxItem item in lb.SelectedItems)   
            {   
                copyContent += item.Content.ToString();   
                // Add a NewLine for carriage return   
                copyContent += Environment.NewLine;   
            }   
            Clipboard.SetText(copyContent);   
        }   
        void CopyCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)   
        {   
            ListBox lb = e.OriginalSource as ListBox;   
            // CanExecute only if there is one or more selected Item.   
            if (lb.SelectedItems.Count > 0)   
                e.CanExecute = true;   
            else  
                e.CanExecute = false;   
        }   
Permalink

With a listbox like this defined in your XAML:

[XAML]
<ListBox x:Name='myLB' ></ListBox>

You can do so in your code-behind as follows:

[C#]
        public MyWindow()
        {
            InitializeComponent();

            Binding binding = new Binding();
            binding.Source = this;
            PropertyPath path = new PropertyPath('ListSource');
            binding.Path = path;
            // Setup binding:
            BindingOperations.SetBinding(this.myLB, ListBox.ItemsSourceProperty, binding);
        }

        public string[] ListSource
        {
            get { return new string[] { 'testing', 'test1' };}
        }
Permalink

You can change the colors in your ListBox’s resources, as follows:

[XAML]
<ListBox>
            <ListBox.Resources>
                <SolidColorBrush x:Key='{x:Static SystemColors.HighlightBrushKey}' Color='White'/>
                <SolidColorBrush x:Key='{x:Static SystemColors.HighlightTextBrushKey}' Color='Black'/>
                <SolidColorBrush x:Key='{x:Static SystemColors.ControlBrushKey}' Color='White'/> 
            </ListBox.Resources>
</ListBox>

The 3rd color above is the gray color in which the selected item background is rendered when the listbox does not have the focus.

Permalink

By default when you bind the ListBox’s ItemsSource to a collection of objects of a custom type, the ListBox would simply call the object’s ToString() method to determine what to display for each item. The ToString method would normally simply display the type name of the object.

If you instead want a value of a property of the object to be displayed in the listbox, you should set the DisplayMemberPath property of the ListBox to that property name as follows:


<ListBox ItemsSource='{StaticResource myCollection}' DisplayMemberPath='FirstName' />
Permalink

The ListBox, like the other ItemsControl can be bound to any IList, ObservableCollection or ObjectDataProvider (containing a list type data) as explained in this MSDN topic:

ItemsControl Content Model Overview

If bound to an ObservableCollection, changes happening in the collection will automatically reflect in the ListBox.

You can also bind to XML Data using an XMLDataProvider as explained in this topic:

How to: Bind to XML Data Using an XMLDataProvider and XPath Queries

Bind the ListBox to a CollectionViewSource to be able to bind to sorted or grouped views of your list.

CollectionViewSource Class

You can also bind to a DataTable in an ADO.NET DataSet as follows:

How to: Bind to an ADO.NET Data Source

Permalink

A ListBox can be bound with a string array using the ItemsSource property of the ListBox control. The following code snippet is used to bind a string array with the ListBox.

[XAML]

<Window x:Class='WpfApplication4.Window1'
    xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
    Title='Window1' Height='300' Width='300' Loaded='Window_Loaded'>
    <Grid>
       <ListBox Name='LB2'/>
    </Grid>
</Window>
[C#]

private void Window_Loaded(object sender, RoutedEventArgs e)
{
string[] lbitems = { 'Item1', 'Item2', 'Item3', 'Item4' };
      LB2.ItemsSource = lbitems;
}
Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.