0

I have a listbox with an image using this same method found here.

It's a listbox with an items template that has an image and textblock. How do I get the listbox's selected value back?

Like so:

string x = listbox.SelectedValue.ToString();

That doesn't give me the text block's value. Any ideas?

ANSWER:

Here is the answer:

 listboxBinding_Master.Detail.SampleData selectedValue = (listboxBinding_Master.Detail.SampleData)listBox1.SelectedItem;
 string x = selectedValue.ListBoxText;

Sampledata is the class I used to define the strings, ListBoxText is the name of the TextBlock.

1
  • Have you set the SelectedValuePath on the ListBox? Commented Mar 13, 2012 at 18:06

1 Answer 1

3

Set the ListBox.SelectedValuePath to the Name of the Member in the Binded class that represents the value you need. This way you should be able to retrieve the value via ListBox.SelectedValue

Edit (example):

<ListBox x:Name="TestListBox" ItemsSource="{Binding}" SelectedValuePath="LastName" MouseDoubleClick="TestListBox_MouseDoubleClick">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=FirstName}" Width="110" />
        <TextBlock Text="{Binding Path=Age}"/>
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

CodeBehind:

public partial class MainWindow: Window
  {
    public MainWindow( )
    {
      InitializeComponent( );
      var persons = new System.Collections.ObjectModel.ObservableCollection<Person>();
      persons.Add( new Person( ) { FirstName = "Walter" , LastName = "Bishop" , Age = 63 } );
      persons.Add( new Person( ) { FirstName = "Peter" , LastName = "Bishop" , Age = 33 } );
      persons.Add( new Person( ) { FirstName = "Olivia" , LastName = "Dunham" , Age = 33 } );
      TestListBox.DataContext = persons;
    }
    private void TestListBox_MouseDoubleClick( object sender , MouseButtonEventArgs e )
    {
      if ( TestListBox.SelectedItem != null )
      {
        MessageBox.Show( (string)TestListBox.SelectedValue );
      }
    }
  }

  public class Person
  {
    public string FirstName { get; set; }
    public string LastName{get;set;}
    public int Age { get; set; }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

can you give me an example of this?
I added the example. SelectedItem will remain an instance of Person btw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.