微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,也失败了.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐