简体   繁体   中英

What is the alternative for DisplayMemberPath=“Value” for Windows Store applications?

I think there is a bug with Windows Store Applications when it comes to using DisplayMemberPath="Value".

Here is my code

    <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;

If you use this code in WPF in works perfectly. However if you use this code in a Windows Store Application then the Combo Box is empty and an error is thrown. So is there an alternative way to do this in Windows Store Applications and have I unearthed a bug? Because I have researched the Web for days and found no solution to this.*please do not comment unless you have tried my code as a Windows Store App not a WPF in Visual Studios.

I've been able to reproduce it in a Universal App (Windows phone version).

To solve it, first remove the "Height" property value on your combobox, because it will prevent the combobox to show you the options when you open it (on Windows Phone at least).

Then, in your code behind, try converting your Dictionnary into a list (or another Dictionnary) of objects (I used anonymous objects, but you better create a custom Type) :

comboBox1.ItemsSource = formateDSource.Select(f => new { Key = f.Key, Value = f.Value }).ToList();

So my xaml looks like this :

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

Right now, I don't really understand what's going on with a raw Dictionnary, but at least you should have a workaround now.

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