创建&#34;字典<string,dictionary <string,=“”string =“”>&gt;&#34;在XAML中</string,>

时间:2014-05-02 07:25:13

标签: c# xaml dictionary

我最近开始使用WPF,并通过这样做介绍了XAML。

我想知道是否可以在XAML中创建Dictionary< string, Dictionary< string, string>>

我知道你可以创建一个Dictionary< TKey, TValue>但是,我似乎无法将字典作为字典的TValue。

任何人都可以帮助我吗?

这是我的词典类。

public class DictionaryForXAML : 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 dictionaryType = type.MakeGenericType(KeyType, ValueType);
                _dictionary = (IDictionary)Activator.CreateInstance(dictionaryType);
            }
            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);
    }

    //Additional inherited methods not posted
}
}

我的XAML Window资源:

<Window.Resources>
    <Class:DictionaryForXAML x:Key="ValueDic" KeyType="System:String" ValueType="System:String"/>
    <Class:DictionaryForXAML x:Key="RootDic" KeyType="System:String" ValueType="???"/>
</Window.Resources>

2 个答案:

答案 0 :(得分:1)

不确定我是否理解你的问题,但是你尝过类似的东西吗?

    <Class:DictionaryForXAML x:Key="RootDic" KeyType="system:String">
        <Class:DictionaryForXAML.ValueType>
            <Class:DictionaryForXAML KeyType="system:String" ValueType="system:String"/>
        </Class:DictionaryForXAML.ValueType>
    </Class:DictionaryForXAML>

<小时/> 编辑:

我尝试了别的东西,这适合你吗?

<强> XAML

<wpfApplication3:RootDictionary x:Key="RootDic">
    <wpfApplication3:SubDictionary x:Key="RootNodeA">
        <system:String x:Key="SubNode1">Test info1</system:String>
        <system:String x:Key="SubNode11">Test info1.1</system:String>
    </wpfApplication3:SubDictionary>  
    <wpfApplication3:SubDictionary x:Key="RootNodeB">
        <system:String x:Key="SubNode2">Test info2</system:String>
    </wpfApplication3:SubDictionary>
</wpfApplication3:RootDictionary>  

<强>代码

using System.Collections.Generic;

namespace WpfApplication3
{
    public class RootDictionary : Dictionary<string, IDictionary<string, string>>
    {

    }

    public class SubDictionary : Dictionary<string, string>
    {

    }
}

答案 1 :(得分:0)

我假设您可以从开头定义词典的性质:

Dictionary< string, Dictionary< string, string>> myDict=new Dictionary< string, Dictionary< string, string>>();

public void Add(string s, Dictionary< string, string> Dict)
{
    if (!myDict.ContainsKey(s))
    {
        myDict.Add(s,Dict)
    }
}