加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 03:58:40 所属栏目:Windows 来源:网络整理
导读:我已经阅读了很多关于将Dictionary绑定到 WPF ListView和ListBox的帖子,但我无法获得在WinRT中工作的等效代码. Grid Margin="10" Width="1000" VerticalAlignment="Stretch" ListBox Name="StatListView" ItemsSource="{Binding FooDictionary}" ListBox.Ite
我已经阅读了很多关于将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,也失败了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读