2010-02-23 75 views
20

伪例如:在xaml中创建一个词典?

<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> 
+0

更多了最新的讨论在https://stackoverflow.com/问题/ 2494823/binding-dictionaryt-to-a-wpf-listbox – Ben 2018-02-26 19:14:48

回答

27

您不能直接在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> 
+0

*在下一个版本的XAML中可能会有什么意思*当你计划实施它时你有任何线索吗? – Shimmy 2010-04-13 13:08:41

+0

@Shimmy:实际上,它已在XAML 2009中实施。不幸的是,VS2010目前还不支持XAML 2009:( – 2010-04-13 13:45:13

+2

)有关详细信息,请参阅此视频:http://channel9.msdn.com/pdc2008/TL36/(XAML 2009新功能开始于7'20) – 2010-04-13 13:48:15

5

related question我给了一个answer这说明人们可以如何创建XAML一个通用字典没有XAML 2009年的功能使用自定义改为Markup Extension

+0

我检查过。这很好! – Shimmy 2012-02-26 03:42:50

+0

@Shimmy:谢谢:) – 2012-02-26 03:43:11

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> 
+1

命名空间声明:'xmlns:Specialized =“clr-namespace:System.Collections.Specialized; assembly = System”' – Pollitzer 2016-02-28 09:41:26

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> 
+0

旧的帖子的新答案,但正是我需要的。 – Pat 2016-10-11 19:05:46