ARTICLE

Get selected item from ListBox in WPF

Posted by Sapna Articles | WPF using VB.NET October 25, 2010
In this article you will see how to get selected item from ListBox in WPF Application.
 
Reader Level:

The ListBox control displays a list of items. The user can select one or multiple items depending on the selection mode. Here we will create an application in which, I have a ListBox with a list of colors, a TextBox, and a Ellipse.

When we pick a color from the ListBox, the text of TextBox and color of Ellipse changes dynamically to the color selected in the ListBox. Lets see the following XAML code snippet:


Xaml Code

<
Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="WpfApplication1.CompileXamlWindow.CompileXamlWindow"
        Title="Compile XAML Window"
        SizeToContent="WidthAndHeight"
        ResizeMode="CanMinimize">
    <StackPanel Orientation="Vertical">
 
        <TextBlock Margin="10,10,10,10" FontWeight="Bold">
          Pick a color from below list 
        
</TextBlock>
 
        <ListBox Name="mcListBox" Height="100" Width="100"
             Margin="10,10,0,0" HorizontalAlignment="Center">
            <ListBoxItem>Orange</ListBoxItem>
            <ListBoxItem>Green</ListBoxItem>
            <ListBoxItem>Blue</ListBoxItem
            <ListBoxItem>Gray</ListBoxItem
            <ListBoxItem>LightGray</ListBoxItem>
            <ListBoxItem>Red</ListBoxItem>
        </ListBox>
        <TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Center" >
            <TextBox.Text>
                <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>
            </TextBox.Text>
 
       </TextBox>
        <Ellipse Stroke="Black" StrokeThickness="1"
                 Height="115" Width="148" ToolTip="An author.">
                 <Ellipse.Fill>
                <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>
            </Ellipse.Fill>
        </Ellipse>
    </StackPanel>
</
Window>

The output of the above code looks like:

listbox.gif

Summary


In this article, I discussed how to select item from ListBox. I hope you will enjoy this article.

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Diagram
Become a Sponsor