在xaml中创建一个字典?

时间:2010-02-23 15:13:01

标签: xaml dictionary key-value idictionary

伪示例:

<Window>
  <Window.Tag>
    <x:Dictionary KeyType="{x:Type sys:String}" ValueType="{x:Type sys:Int32}">
        <sys:DictionaryEntry Entry="{sys:DictionaryEntry Key0, 000}"/>
        <sys:DictionaryEntry Key="key1" Value="111"/>
        <sys:DictionaryEntry>
          <sys:DictionaryEntry.Key>
            <sys:String>Key2<sys:String>
          </sys:DictionaryEntry.Key>          
          <sys:DictionaryEntry.Value>
            <sys:Int32>222</sys:Int32>            
          </sys:DictionaryEntry.Value>
        </sys:DictionaryEntry>
    </x:Dictionary />    
  </Window.Tag>
</Window>

4 个答案:

答案 0 :(得分:30)

您不能直接在XAML中使用Dictionary<TKey, TValue>类,因为无法指定泛型类型参数(在下一版本的XAML中可以使用它,但在VS2010中不支持它) WPF设计师......至少在初始版本中没有。)

但是,您可以声明一个继承自Dictionary<TKey, TValue>的非泛型类,并在XAML中使用它。

<强> C#

public class MyDictionary : Dictionary<string, int> { }

<强> XAML

<Window>
  <Window.Tag>
    <local:MyDictionary>
        <sys:Int32 x:Key="key0">0</sys:Int32>
        <sys:Int32 x:Key="key1">111</sys:Int32>
        <sys:Int32 x:Key="key2">222</sys:Int32>
    </local:MyDictionary />    
  </Window.Tag>
</Window>

答案 1 :(得分:6)

如果键和值是字符串,则可以使用ListDictionary或HybridDictionary。

例如:

<Specialized:ListDictionary x:Key="MasterSlidesFileNames">
    <System:String x:Key="long">Ya long yes ni</System:String>
    <System:String x:Key="Sun">Waterfall</System:String>
    <System:String x:Key="lorem ipsum">hello wOrld</System:String>
</Specialized:ListDictionary>

答案 2 :(得分:5)

related question中,我提供了一个answer,其中显示了如何使用自定义Markup Extension而不使用XAML 2009功能在XAML中创建通用字典。

答案 3 :(得分:4)

尝试这样的事情:

使用此命名空间:xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"

<ComboBox.ItemsSource>
    <collections:ArrayList>
        <collections:DictionaryEntry Key="0" Value="Standby"/>
        <collections:DictionaryEntry Key="1" Value="Maintenance"/>
        <collections:DictionaryEntry Key="2" Value="Available"/>
        <collections:DictionaryEntry Key="3" Value="Deselected"/>
        <collections:DictionaryEntry Key="4" Value="Input Error"/>
    </collections:ArrayList>
</ComboBox.ItemsSource>