Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind a listbox selecteditem content to a textbox?

Tags:

linq

binding

wpf

I have a listbox thats getting binded by this query when TextName content changes:

var players =
    from p in context.Player
    where p.GivenName.StartsWith(TextName.Text.Trim())
    select p;

listNames.ItemsSource = players.ToList();

It shows the players names that starts with the text on the textbox. Now when I click any Item (name) from the listbox I need that the TextName shows the player name that's selected on the listbox. I tried to bind it this way:

<TextBox ... Text="{Binding Source=listNames, Path=SelectedItem.Content}" ... />

But when I click a ListboxItem, the textbox just get cleared and does not show anything.. may I have to set up the textbox like I do with the listbox when setting the DisplayMemeberPath???? I need a only one way binding!! What can I do??

like image 578
Max Avatar asked Sep 21 '11 17:09

Max


2 Answers

You have 2 problems with your binding:

  1. You are using the Source property instead of the ElementName to specify the list box name
  2. You are trying to bind to a Content property which (I am assuming) does not exist on your Player object. This happens because the SelectedItem property of the ListBox is an instance of Player when you specify an ItemsSource as you have

To solve this you should change your binding to the following:

<TextBox ... Text="{Binding ElementName=listNames, Path=SelectedItem.GivenName}" ... />
like image 54
Steve Greatrex Avatar answered Oct 13 '22 09:10

Steve Greatrex


<TextBox ... Text="{Binding ElementName=listNames, Path=SelectedItem.Name}" ... />

This binds the TextBox.Text to the ListBoxes - called listNames - SelectedItem, which contains Player objects, and you need its Name property.

like image 1
Miklós Balogh Avatar answered Oct 13 '22 08:10

Miklós Balogh