SortedList
很容易使用,因为它不是泛型的。
如果一个类实现了 IDictionary
,您可以通过将其定义为子节点并使用 x:Key
来设置用于将其添加到字典中的键来添加值。
xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
<col:SortedList x:Key="list">
<sys:String x:Key="0">Lorem</sys:String>
<sys:String x:Key="1">Ipsum</sys:String>
<sys:String x:Key="2">Dolor</sys:String>
<sys:String x:Key="3">Sit</sys:String>
</col:SortedList>
<!
<ContentControl Content="{Binding [0], Source={StaticResource list}}" />
这里的项目键是字符串,如果要获取实际的整数,可以使用自定义标记扩展将字符串解析为整数,或者首先将键定义为资源:
<sys:Int32 x:Key="key1">0</sys:Int32>
<sys:Int32 x:Key="key2">1</sys:Int32>
<sys:Int32 x:Key="key3">2</sys:Int32>
<sys:Int32 x:Key="key4">3</sys:Int32>
<col:SortedList x:Key="list">
<sys:String x:Key="{StaticResource key1}">Lorem</sys:String>
<sys:String x:Key="{StaticResource key2}">Ipsum</sys:String>
<sys:String x:Key="{StaticResource key3}">Dolor</sys:String>
<sys:String x:Key="{StaticResource key4}">Sit</sys:String>
</col:SortedList>
绑定过程会变得更加复杂,因为索引器的值需要显式地转换为整型,否则它会被解释为字符串。
<ContentControl Content="{Binding Path=[(sys:Int32)0],
Source={StaticResource list}}"/>
由于一个实现细节,您不能省略Path=
。
字典不太容易处理,因为它们是通用的,而在XAML中没有简单的内置方法来创建通用对象。不过,通过使用标记扩展,您可以通过反射创建通用对象。
在此类扩展上实现 IDictionary
接口也使您能够填充新创建的实例。这里是一个非常基础的示例:
public class DictionaryFactoryExtension : MarkupExtension, IDictionary
{
public Type KeyType { get; set; }
public Type ValueType { get; set; }
private IDictionary _dictionary;
private IDictionary Dictionary
{
get
{
if (_dictionary == null)
{
var type = typeof(Dictionary<,>);
var dictType = type.MakeGenericType(KeyType, ValueType);
_dictionary = (IDictionary)Activator.CreateInstance(dictType);
}
return _dictionary;
}
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Dictionary;
}
public void Add(object key, object value)
{
if (!KeyType.IsAssignableFrom(key.GetType()))
key = TypeDescriptor.GetConverter(KeyType).ConvertFrom(key);
Dictionary.Add(key, value);
}
#region Other Interface Members
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(object key)
{
throw new NotSupportedException();
}
#endregion
}
<me:DictionaryFactory x:Key="dict" KeyType="sys:Int32" ValueType="sys:String">
<sys:String x:Key="0">Lorem</sys:String>
<sys:String x:Key="1">Ipsum</sys:String>
<sys:String x:Key="2">Dolor</sys:String>
<sys:String x:Key="3">Sit</sys:String>
</me:DictionaryFactory>
由于将已键入的实例作为键传递有点麻烦,所以我选择在将值添加到内部字典之前,在IDictionary.Add
中进行转换(这可能会导致某些类型的问题)。
由于字典本身是已键入的,因此绑定不应需要强制转换。
<ContentControl Content="{Binding [0], Source={StaticResource dict}}" />
x:Array
就可以了。只需添加第一个<sys:String>
,它将获得索引0
,然后绑定可以使用[0]
来定位索引器。 - H.B.