0
var list = new List<Dictionary<string, string>>{
                new Dictionary<string,string>{
                    {"id","1"},
                    {"name","foo"},
                }, 
                new Dictionary<string,string>{
                    {"id","2"},
                    {"name","bar"},
                }
            };

I want to bind this list to a listbox. It's quite simple:

listBox.ItemsSource=list;

but the problem is: I can't control what is displayed in the listbox. What I want is to display is dict["name"]. I tried:

listbox.DisplayMemberPath="name"

Sadly it doesn't work.

2 Answers 2

2

Your code tries to display a property called name on the dictionary, which doesn't exist. To access an indexer use the following syntax:

listBox.DisplayMemberPath = "[name]";

Also, you should be probably setting things like this directly in XAML, not in code-behind.

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

2 Comments

Wow, you answered my question one minute before I figured it out myself. And apparently your solution is simpler. thank you!
Actually, I answered it about one minute after you.
0

I figured it out:

<ListBox HorizontalAlignment="Left" Margin="8,35,0,77" Width="88" Name="mainListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path=[name]}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

pay attention to <Label Content="{Binding Path=[name]}" />, it does all the magic.

hope this help somebody in the future :)

2 Comments

You don't need the template in this case at all.
@svick, yes you are right. adding attribute DisplayMemberPath="[name]" is enough in this case. thank you for pointing this out.

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.