【问题标题】:Create a Dictionary in xaml?在 xaml 中创建字典?
【发布时间】:2011-01-20 02:57:36
【问题描述】:

伪例子:

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

【问题讨论】:

标签: xaml dictionary key-value idictionary


【解决方案1】:

试试这样的:

使用这个命名空间: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>

【讨论】:

  • 旧帖子的新答案,但正是我需要的。
【解决方案2】:

如果键和值是字符串,可以使用 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>

【讨论】:

  • 命名空间声明:xmlns:Specialized="clr-namespace:System.Collections.Specialized;assembly=System"
  • xmlns:System="clr-namespace:System;assembly=mscorlib"
【解决方案3】:

related question 中,我给出了answer,它展示了如何在没有XAML 2009 功能的情况下使用自定义Markup Extension 在XAML 中创建通用字典。

【讨论】:

  • 我查过了。是的,很棒!
【解决方案4】:

你不能在 XAML 中直接使用 Dictionary&lt;TKey, TValue&gt; 类,因为没有办法指定泛型类型参数(在下一个版本的 XAML 中将可以,但在 VS2010 WPF 设计器中将不支持...至少在初始版本中没有)。

但是,您可以声明一个继承自 Dictionary&lt;TKey, TValue&gt; 的非泛型类,并在 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>

【讨论】:

  • 在 XAML 的下一个版本中将有可能是什么意思,你知道他们计划何时实现它吗?
  • @Shimmy :实际上,它已经在 XAML 2009 中实现了。不幸的是 VS2010 还不支持 XAML 2009 :(
  • 有关详细信息,请观看此视频:channel9.msdn.com/pdc2008/TL36(XAML 2009 新功能从 7'20 开始呈现)
  • 你是什么意思7'20,这是我70岁的时候吗:{
  • 我指的是视频中“7分20秒”的位置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 2014-06-12
相关资源
最近更新 更多