通过使用转换对象的转换器绑定到任意字典<,>
本文关键字:任意 字典 绑定 转换器 转换 对象 | 更新日期: 2023-09-27 18:32:52
我正在尝试解决在WinRT Xaml中绑定到字典的困难(也引用了此处)。 我想使用转换器来执行此操作,而不必更改我的所有视图模型或业务代码来返回自定义键值类的列表。
这意味着我需要将对象转换为某种类型的列表<>。
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
。或者你可以使用字典的值 - 或其键。例如:
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;
我找到了一个解决方案...有效,但我真的不喜欢它。我不确定这是否会在稳定性或性能方面产生任何意想不到的后果。
词典转换器
使用自定义类和列表以及动态来转换字典。
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 中绑定任何类型的字典<,>对象。