shaun
shaun

Reputation: 35

Selecting an item in a listbox through binding with a textbox

I have a listbox that is populated with a list of objects that has two properties. One of these properties is displayed in the listbox, and the other gets displayed in a textbox through binding. I am wondering if there is a way I can change the selection on the listbox by changing the value of the textbox, as I can't use selected index, or selected Item

Upvotes: 2

Views: 385

Answers (1)

Daniel Pratt
Daniel Pratt

Reputation: 12077

Just to give you an example, I'm going to suppose that you have a list of customers and the Customer.Name property is displayed in the list box, and the Customer.Id property is displayed in the text box. You can setup the bindings this way:

<ListBox
    x:Name="CustomerList"
    DisplayMemberPath="Name"
    SelectedValuePath="Id"
    SelectedValue="{Binding ElementName=CustomerId, Path=Text}" />
<TextBox x:Name="CustomerId" />

Now as Customers are selected in the CustomerList list box, their respective Id values appear in the CustomerId text box. More importantly, the reverse also works: type a valid Id in the text box, and the corresponding Customer will become selected in the list box.

Upvotes: 2

Related Questions