WPF binding List<Dictionary<string,string>> to a ListBox

落爺英雄遲暮 提交于 2020-01-17 01:39:49

问题


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.


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/6236829/wpf-binding-listdictionarystring-string-to-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!