WPF绑定List <dictionary <string,string>&gt;到ListBox </dictionary <string,string>

时间:2011-06-04 12:49:05

标签: wpf data-binding listbox

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

我想将此列表绑定到列表框。这很简单:

listBox.ItemsSource=list;

但问题是:我无法控制列表框中显示的内容。我想要的是显示dict [“name”]。我试过了:

listbox.DisplayMemberPath="name"

可悲的是它不起作用。

2 个答案:

答案 0 :(得分:2)

您的代码尝试在字典上显示名为name的属性,该属性不存在。要访问索引器,请使用以下语法:

listBox.DisplayMemberPath = "[name]";

另外,你可能应该直接在XAML中设置这样的东西,而不是在代码隐藏中。

答案 1 :(得分:0)

我明白了:

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

注意<Label Content="{Binding Path=[name]}" />,它会带来所有魔力。

希望这有助于将来某人:)