我已经阅读了很多关于将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;
}
}
Run Code Online (Sandbox Code Playgroud)
什么是正确的绑定?
输出窗口中的错误是(修剪到最有用的部分):
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, ....
Run Code Online (Sandbox Code Playgroud)
在内部,WinRT将类型转换为:
System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl<K, V>
Run Code Online (Sandbox Code Playgroud)
如果您添加到DataTemplate:
<TextBlock Text="{Binding}" Margin="5" />
Run Code Online (Sandbox Code Playgroud)
你会看到它发出上面的类型String, String.
但是,出于某种原因,它没有按预期正确处理.如果您在Internet上搜索该类型,您将看到有关Connect上的问题的文档错误.
一个简单的解决方法是将数据放在一个不是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; }
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,至少从简单的测试来看,根本不是导致问题的字典,而是它是一个KeyValuePair被转换为上述CLRIKeyValuePairImpl类型的对象实例.我尝试使用列表并向KeyValuePair<string, string>List 添加实例,但也失败了.
| 归档时间: |
|
| 查看次数: |
2757 次 |
| 最近记录: |