21

伪示例:

<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

4 回答 4

32

您不能Dictionary<TKey, TValue>直接在 XAML 中使用该类,因为无法指定泛型类型参数(在 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>
于 2010-02-23T16:14:22.767 回答
7

如果键和值是字符串,则可以使用 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>
于 2013-06-24T14:49:58.717 回答
5

在一个相关问题中,我给出了一个答案,它展示了如何在没有 XAML 2009 功能的情况下使用自定义标记扩展来创建 XAML 中的通用字典。

于 2012-02-26T02:44:48.600 回答
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>
于 2016-06-30T21:22:54.187 回答