Binding a Dictionary to a WinRT ListBox

前端 未结 2 703
无人共我
无人共我 2020-12-10 18:26

I\'ve read a number of posts on binding Dictionary to WPF ListView and ListBox but I can\'t get equivalent code to work in WinRT.



        
2条回答
  •  自闭症患者
    2020-12-10 19:11

    The error in the output window is (trimmed to the most useful part):

    Error: Cannot get 'Key' value (type 'String') from type 
    'System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl`2
    [[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, 
    PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, 
    Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, ....
    

    Internally, WinRT is converting the type to:

    System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl
    

    If you add to your DataTemplate:

    
    

    You'll see that it emits the above type with String, String.

    However, for some reason, it's not being properly handled as expected. If you search for that type on the Internet, you'll see that there's a documented bug for the issue on Connect.

    A simple work around would be to place your data in a simple object that is not a KeyValuePair:

    List temp = new List();
    temp.Add(new StringKeyValue { Key = "key1", Value = "value1" } );
    temp.Add(new StringKeyValue { Key = "key2", Value = "value2" });
    temp.Add(new StringKeyValue { Key = "key3", Value = "value3" });
    temp.Add(new StringKeyValue { Key = "key4", Value = "value4" });
    
    this.DefaultViewModel["FooDictionary"] = temp;
    
    public class StringKeyValue
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
    

    As an aside, from a simple test at least, it's not the Dictionary that's causing the issue at all, it's the fact that it's a KeyValuePair object instance that's being converted to the CLRIKeyValuePairImpl type mentioned above. I tried just using a list and adding a KeyValuePair instance to a List, and that failed as well.

提交回复
热议问题