通过使用转换器来转换对象来绑定到任意 Dictionary<,>

Bind to arbitrary Dictionary<,> by using a converter to cast object

我正在尝试解决 difficulties in binding to a Dictionary in WinRT Xaml (also referenced here)。我想使用转换器来执行此操作,而不必将我所有的视图模型或业务代码更改为 return 自定义键值列表 class。

这意味着我需要将对象转换为某种类型的 List<>。

    public object Convert(object value, Type targetType, object parameter, string temp)
    {
        if(value is IDictionary)
        {
            dynamic v = value;

            foreach (dynamic kvp in v)
            {

            }
        }
        return //some sort of List<>
    }

虽然我不知道该怎么做。当我将鼠标悬停在调试器中的值上时,它仍然记得它的适当类型(如字典),但我不知道如何在 运行 时间使用它。主要问题是 Convert 函数在编译时不知道键或值的类型,因为我使用了多种类型的字典。

我需要做什么才能将对象类型(保证实际上是字典<,>)转换为某种列表,以便我可以在 XAML?

字典根本不是列表;您无法将其转换为某种类型的 List<>。不过,它是一个 IEnumerable,因此您可以迭代它的 KeyValuePair。或者您可以使用字典的 values 或其键。例如:

IDictionary<string, string> dictionary = value as IDictionary<string, string>;
if (dictionary != null)
{
    ICollection<string> keys = dictionary.Keys;
    ICollection<string> values = dictionary.Values;

    // Either of those can be bound to a ListView or GridView ItemsSource
    return values;
}

return null;

将您使用的任何类型替换为 string。或者使用非通用版本:

IDictionary dictionary = value as IDictionary;
if (dictionary != null)
{
    ICollection keys = dictionary.Keys;
    ICollection values = dictionary.Values;

    // Either of those can be bound to a ListView or GridView ItemsSource
    return values;
}

return null;

我找到了一个解决方案...有效,但我不太喜欢它。我不确定这是否会对稳定性或性能产生任何意想不到的后果。

字典转换器

使用自定义 class 和列表以及动态转换字典。

    public object Convert(object value, Type targetType, object parameter, string temp)
    {
        List<CustomKeyValue> tempList = new List<CustomKeyValue>();

        if(value is IDictionary)
        {
            dynamic v = value;

            foreach (dynamic kvp in v)
            {
                tempList.Add(new CustomKeyValue() { Key = kvp.Key, Value = kvp.Value });
            }
        }

        return tempList;
    }

    public class CustomKeyValue
    {
        public dynamic Key { get; set; }
        public dynamic Value { get; set; }
    }

这允许绑定工作,幸运的是我只需要是单向的

XAML

        <ListView ItemsSource="{Binding MyDictionary, Converter={StaticResource DictionaryConverter}}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Key}"/>
                        <TextBlock Text="  :  "/>
                        <TextBlock Text="{Binding Value}"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

因此,使用该转换器,我可以在 XAML.

中绑定任何类型的 Dictionary<,> 对象