如何在WPF中将Dictionary绑定到Combobox

时间:2018-02-19 14:07:00

标签: c# wpf binding

当我将FoundItems字典绑定到ComboBox时,ComboBoxItems项变为[1, FoundItem], [2, FoundItem] ...

但我希望将RecordName绑定为显示的值RecordID or Dictionary's Key作为选定项。 并且,SelectedItemID应该与TwoWay绑定到ComboBox。

我试图在2天内实现这一目标。但仍然没有结果。

public int SelectedItemID { get; set; }
public Dictionary<int, FoundItem> FoundItems { get; set; }


    FoundItems = new Dictionary<int, FoundItem>
    {
        { 1, new FoundItem() { RecordID = 1, RecordName = "Test Name 1" } },
        { 2, new FoundItem() { RecordID = 2, RecordName = "Test Name 2" } },
        { 3, new FoundItem() { RecordID = 3, RecordName = "Test Name 3" } },
        { 4, new FoundItem() { RecordID = 4, RecordName = "Test Name 4" } }
    };

FoundItem类:

internal class FoundItem
{
    public int RecordID { get; set; }
    public string RecordName { get; set; }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

<ComboBox ItemsSource="{Binding FoundItems}" DisplayMemberPath="Value.RecordName"
          SelectedValuePath="Value.RecordID"
          SelectedValue="{Binding SelectedItemID}"/>