我读过一些有约束力的解释,以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, mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, ....
在内部,WinRT的是类型转换为:
System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl<K, V>
如果您添加到您的DataTemplate:
<TextBlock Text="{Binding}" Margin="5" />
你会看到,它发出的上述类型与String, String
。
然而,由于某些原因,它没有被正确地预期处理。 如果您搜索类型在互联网上,你会看到有一个记录的缺陷对连接的问题。
一个简单的解决办法是把你的数据在一个简单的对象不是一个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>
实例列表,并且也失败了。
我想出了一个解决办法,这涉及动态生成自己的键值对。
如果你已经专门解释,只补充一点:
public IEnumerable<MyPair<K, V>> Collection
{
get {
foreach (var v in this)
{
MyPair<K, V> p = new MyPair<K, V>() { Key = v.Key, Value = v.Value };
yield return p;
}
}
}
并定义对类型:
public class MyPair<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
}
此外,应注意在创建新对象每次。 有些项目徒步穿越的对象,并存储回报,这可能导致一切看起来像的最后一个项目,如果你试图重用MyPair就像我本来。