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

本秂侑毒 提交于 2019-12-31 03:45:10

问题


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?


回答1:


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;



回答2:


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

comboBox1.DisplayMemberPath = ".";


来源:https://stackoverflow.com/questions/29777530/displaymemberpath-gives-an-error-when-i-try-to-use-it-to-display-the-value-of-my

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