windows-runtime – 将字典绑定到WinRT ListBox

我已经阅读了很多关于将Dictionary绑定到 WPF ListView和ListBox的帖子,但我无法获得在WinRT中工作的等效代码.

<Grid Margin="10" Width="1000" VerticalAlignment="Stretch">
        <ListBox Name="StatListView" ItemsSource="{Binding FooDictionary}" >
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <Grid Margin="6">
                        <StackPanel Orientation="Horizontal" >
                            <TextBlock Text="{Binding Key}" Margin="5" />
                            <TextBlock Text="{Binding Value}" Margin="5" />
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>


    public Dictionary<string,string> FooDictionary
    {
        get
        {
            Dictionary<string,string> temp = new Dictionary<string,string>();
            temp.Add("key1","value1");
            temp.Add("key2","value2");
            temp.Add("key3","value3");
            temp.Add("key4","value4");
            return temp;
        }
    }

什么是正确的绑定?

解决方法

输出窗口中的错误是(修剪到最有用的部分):

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,PublicKeyToken=b77a5c561934e089]],....

在内部,WinRT将类型转换为:

System.Runtime.InteropServices.WindowsRuntime.CLRIkeyvaluePairImpl<K,V>

如果您添加到DataTemplate:

<TextBlock Text="{Binding}" Margin="5" />

您将看到它使用String,String发出上述类型.

但是,出于某种原因,它没有按预期正确处理.如果您在Internet上搜索该类型,您将看到Connect上的问题有一个documented bug.

一个简单的解决方法是将数据放在一个不是keyvaluePair的简单对象中:

List<Stringkeyvalue> temp = new List<Stringkeyvalue>();
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; }
}

顺便说一下,至少从简单的测试来看,根本不是导致问题的字典,而是它是一个keyvaluePair对象实例,它被转换为上面提到的CLRIkeyvaluePairImpl类型.我尝试使用列表并添加keyvaluePair< string,string>实例到List,也失败了.

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...