【问题标题】:WPF binding List<Dictionary<string,string>> to a ListBoxWPF 将 List<Dictionary<string,string>> 绑定到 ListBox
【发布时间】:2011-06-04 12:49:04
【问题描述】:
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"

很遗憾,它不起作用。

【问题讨论】:

    标签: wpf data-binding listbox


    【解决方案1】:

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

    listBox.DisplayMemberPath = "[name]";
    

    另外,您可能应该直接在 XAML 中设置类似的内容,而不是在代码隐藏中。

    【讨论】:

    • 哇,您在我自己弄清楚之前一分钟就回答了我的问题。显然你的解决方案更简单。谢谢!
    • 其实我比你晚一分钟才回答。
    【解决方案2】:

    我想通了:

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

    注意&lt;Label Content="{Binding Path=[name]}" /&gt;,它会变魔术。

    希望这对将来的某人有所帮助:)

    【讨论】:

    • 在这种情况下你根本不需要模板。
    • @svick,是的,你是对的。在这种情况下,添加属性 DisplayMemberPath="[name]" 就足够了。感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 2018-08-04
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多