简体   繁体   中英

DisplayMemberPath gives an error when I try to use it to display the value of my dictionary in a Combo Box

Here is my Combo Box

<ComboBox Height="40" VerticalAlignment="Stretch" x:Name="comboBox1" Grid.Column="1" FontSize="25">
        </ComboBox>

Here is my C# code

var source = new Dictionary<string, double>();
        source.Add("Item1", 0.4);
        source.Add("Item2", 0.3);
        source.Add("Item3", 0.1);
        source.Add("Item4", 0.1);

        var formateDSource = new Dictionary<string, string>();

        foreach (var item in source)
        {
            formateDSource.Add(string.Format("[{0}, {1}]", item.Key, item.Value), item.Key);
        }

        comboBox1.ItemsSource = source.Values;
        comboBox1.DisplayMemberPath = "Value";

When I run my code I don't see anything in the Combo Box. What have I done wrong?

Try this:

<ComboBox Height="40" VerticalAlignment="Stretch" SelectedValuePath="Key" DisplayMemberPath="Value" x:Name="comboBox1" FontSize="25"/>

var source = new Dictionary<string, double>();
            source.Add("Item1", 0.4);
            source.Add("Item2", 0.3);
            source.Add("Item3", 0.1);
            source.Add("Item4", 0.1);

            var formateDSource = new Dictionary<string, string>();

            foreach (var item in source)
            {
                formateDSource.Add(string.Format("[{0}, {1}]", item.Key, item.Value), item.Key);
            }

            comboBox1.ItemsSource = source;

you should try '.' instead of Value, it should pick it up as binding to the object as it has no property name

comboBox1.DisplayMemberPath = ".";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM