如何直接绑定到Windows Phone 8.1中的字典

时间:2015-09-08 12:57:17

标签: c# windows-phone-8 windows-phone-8.1 windows-8.1

我有Dictionary<string,string>我需要直接绑定到Windows Phone 8.1中的ListViewListView定义如下:

<ListView ItemsSource="{Binding Path=Companies}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Key}" />
                        <TextBlock Text="{Binding Path=Value}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

我的词典已经被初始化了一些随机值。

Companies = new Dictionary<string, string>
            {
                {"abc","hello" },
                {"def","listen" },
                {"ghi","please" },
                {"jkl","help" }
            };

我收到以下错误。

  

错误:无法从类型中获取“值”值(键入“String”)   “System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl 2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'. BindingExpression: Path='Value' DataItem='System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl -2 - [[System.String,   mscorlib,版本= 4.0.0.0,文化=中性,   PublicKeyToken = 7cec85d7bea7798e],[System.String,mscorlib,   Version = 4.0.0.0,Culture = neutral,PublicKeyToken = 7cec85d7bea7798e]],   mscorlib,版本= 4.0.0.0,文化=中性,   公钥= 7cec85d7bea7798e';目标元素是   'Windows.UI.Xaml.Controls.TextBlock'(Name ='null');目标属性是   '文字'(输入'String')。

1 个答案:

答案 0 :(得分:1)

尝试将您的逻辑封装到一个类中并使用ObservableCollection&#39;&lt;&#39;而不是使用Dictionary&#39;&lt;&#;; string,string&#39;&gt;&#39; YourType&#39;&GT;&#39 ;.例如,假设你有

public class Car
{
   public string Make{get;set;}
   public string Model{get;set;}
}

然后,在你的xaml中你会得到:

<ListView ItemsSource="{Binding Path=Companies}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Make}" />
                    <TextBlock Text="{Binding Path=Model}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
</ListView>