向 ResourceDictionary 添加 SortedList 或 Dictionary<int, string>

10

有没有一种方法可以将SortedList或Dictionary添加到ResourceDictionary中,并通过XAML将其用于(和绑定!)控件?

我尝试过这个,但我无法弄清楚如何做到:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:coll="clr-namespace:System.Collections.Generic;assembly=mscorlib">

    <x:Array x:Key="test"
             Type="sys:Object">
        <coll:KeyValuePair>***</coll:KeyValuePair>
    </x:Array>

如果您按顺序添加,那么x:Array就可以了。只需添加第一个<sys:String>,它将获得索引0,然后绑定可以使用[0]来定位索引器。 - H.B.
1个回答

18

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>
<!-- Usage: -->
<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();
    }
    // <Many more members that do not matter one bit...>
    #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}}" />

这在 Silverlight 4 中不适用,我尝试添加 MarkupExtension 但即使添加了命名空间也不存在,有没有什么解决方法? - AMH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接