问题描述
我正在尝试解决绑定到字典方面的困难(也称为此处).我想使用转换器来执行此操作,而不必更改所有视图模型或业务代码以返回自定义键值类的列表.
I'm trying to workaround the difficulties in binding to a Dictionary in WinRT Xaml (also referenced here). I want to use a converter to do this rather than having to change all of my view-models or business code to return a List of a custom Key Value class.
这意味着我需要将对象转换为某种类型的列表.
This means I need to cast an object to a List<> of some type.
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<>
}
我不知道该怎么做.当我将鼠标悬停在调试器中的值上时,它仍然记住其适当的类型(例如Dictionary),但是我不知道如何在运行时使用它.主要问题在于,由于我使用的是多种类型的字典,因此Convert函数在编译时将不知道键或值的类型.
I don't know how to do this though. When I mouse over the value in the debugger it still remember its appropriate type (like Dictionary) but I don't know how to make use of this at run time. The main problem is that the Convert function won't know the types of the Keys or Values at compile time because I'm using multiple types of Dictionaries.
我需要怎么做才能将类型为object的对象(保证实际上是一个Dictionary<,>)转换为某种List,以便可以在XAML中绑定到它?
推荐答案
我找到了一种可行的解决方案,但我并不喜欢它.我不确定这是否会对稳定性或性能产生任何意想不到的后果.
I've found a solution which...works, but I don't really like it. I'm not sure if this has any unintended consequences in terms of stability or performance.
DictionaryConverter
使用自定义类,列表以及整个动态来转换字典.
Uses a custom class and a List as well as dynamics all over to convert the dictionary.
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; }
}
这允许绑定起作用,对我来说幸运的是,只需要单向操作即可.
This allows the binding to work, which fortunately for me only needs to be One-Way
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<,>对象.
So using that converter I can bind any type of Dictionary<,> object in my XAML.
这篇关于绑定到任意Dictionary<,>通过使用转换器来投射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!