【问题标题】:Dictionary<String, String> not binding in xaml (Metro App)Dictionary<String, String> 在 xaml 中未绑定(Metro 应用程序)
【发布时间】:2012-10-23 21:07:12
【问题描述】:

在 ListView 的 DataTemplate 中进行绑定时遇到问题。我的绑定目标是 KeyValuePair。 (我使用适用于 Windows 8 的 Metro App)

我有一本字典

Params = new Dictionary<string, string>();
Params.Add("Key1", "Value1");
Params.Add("Key1", "Value2");

我尝试绑定它:

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

但是 KeyPairValue 对此没有反应(没有绑定)。但如果我做那个绑定:

<ListView ItemsSource="{Binding Params}">
    <ListView.ItemTemplate>
        <DataTemplate>
           <TextBlock Text="{Binding}"></TextBlock>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

我明白了:

早期此绑定在 Windows Phone 7 的应用程序中正常工作。Windows 8 中发生了什么?

【问题讨论】:

    标签: .net xaml binding windows-8 windows-runtime


    【解决方案1】:

    尝试指定Path=

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

    但您可能需要ObservableDictionary

    或者您可能只是遇到了这个错误:http://social.msdn.microsoft.com/Forums/en-AU/winappswithcsharp/thread/234a17ad-975f-42f6-aa91-7212deda4190,我通过谷歌搜索找到了 clrIkeyvaluepairimpl

    【讨论】:

    • 我尝试使用 ObservableDictionary 或指定路径,但没有帮助。 Perhars 这是一个错误。 :(你知道这次怎么解决吗?
    • 不抱歉,点击我发现的错误的链接。
    • 哦,他们关闭了错误...但没有修复
    • 2013 年 2 月 - 仍然无法绑定到字典,有人有任何干净的解决方法吗?我将使用字典的模型包装在一个将它们公开为列表的类中:(
    • @Stony 如果我的回答中的链接对您没有帮助,请尝试提出一个新问题,详细说明您正在做什么。
    【解决方案2】:

    另一种解决方案是使用带有自定义键/值对的列表而不是字典。原因是 IEnumerable> 将用于在绑定期间列出字典中存在的键/值对。问题出在 KeyValuPair,而不是 Dictionary 实际上,因为它被转换为 System.Runtime.InteropServices.WindowsRuntime.CLRIKeyValuePairImpl 并且绑定到此类型时出现问题。

    所以创建一个像这样的类:

    public class XamlFriendlyKeyValuePair<Tkey, TValue> 
    {
        public TKey Key {get; set;}
        public TValue Value {get; set;} 
    }
    

    像这样使用它应该可以解决问题:

    Params = new List<XamlFriendlyKeyValuePair<string, string>>();
    Params.Add{"Key1", "Value1"};
    Params.Add{"Key1", "Value2"};
    

    来源:http://www.sohuaz.xyz/questions/683779/binding-a-dictionary-to-a-winrt-listbox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-15
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多