2

Let's say I have a class Organisation:

public class Organisation(){
   public string Name{
      get;
      set;
   }
   public string Code{
      get;
      set;
   }
}

Then I create an array of Organisation:

public Organisation[] Organisations;

The organisation information is stored in an xml and are filled into the array, which works great.

My problem is, that I'd like to bind the ItemSource of the Combobox to the Name property of my Organisations.

It would be very easy if I just have an array of strings which represent the names:

public string[] OrgansationNames = new string[]{"Organ1", "Organ2" /**/};

I could then easily bind like this:

ItemSource="{Binding Path=OrganisationNames}"

Obviously it is a little more complex and I need something like this:

ItemSource="{Binding Path=Organisations[].Name}"

It is not clear to me how I should specify the Path in this case...

1 Answer 1

3

You can use DisplayMemberPath property:

<ComboBox ...
          ItemSource="{Binding Path=OrganisationNames}"
          DisplayMemberPath="Name" />

Additionally, you can use SelectedValuePath property, which will specifiy the path to the property that is used to determine the value of the SelectedValue property.

<ComboBox ...
          ItemSource="{Binding Path=OrganisationNames}"
          DisplayMemberPath="Name" 
          SelectedValuePath="ID"/>

If you have not any Id, then you can set SelectedValuePath to Name also.

Sign up to request clarification or add additional context in comments.

4 Comments

I tested it and it works (!) without specifying a SelectedValuePath. What is it supposed to solve?
You can remove it, The SelectedValuePath property specifies the path to the property that is used to determine the value of the SelectedValue property.
This is absoluty amazing! I didn't know about SVP. OMG thank you so much. This will save me some calls :) Will accept in 7 min...
@Farhad Jabiyev: just to complete the answer. if you needed to display something more that just a single property in each item, e.g. FirstName and LastName and Photo, you can use ItemTemplate istead of DisplayMemberPath: msdn.microsoft.com/en-us/library/ms742521(v=vs.110).aspx

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.