【问题标题】:Bind Combobox Itemsource to Static Dictionary (Silverlight)将 Combobox Itemsource 绑定到静态字典 (Silverlight)
【发布时间】:2014-06-13 00:33:28
【问题描述】:

我正在尝试将我的 ComboBox 的 ItemsSource 绑定到我在静态类上拥有的静态字典。

在 WPF 中,我会使用以下可以正常工作的方法:

ItemSource="{x:Static objectModel:LocaleHelper.FriendlyNames}"

LocaleHelper 是类名,FriendlyNames 是我希望绑定到的字典属性。
但是,在 Silverlight 中,我收到与类型 x:Static 未找到有关的错误。
谁能向我解释一下问题是什么以及解决方法?
我环顾四周,但找不到任何详细的解释。
对不起,如果这是一个简单的问题 - 我是 Silverlight 和 WPF 的新手。

编辑: 在进行了更多阅读之后,silverlight 似乎不支持静态资源。此外,字典似乎没有更新属性更改/支持DisplayMemberPathSelectedValue,因此在我的视图模型中将字典作为字段似乎也不是一种选择。

【问题讨论】:

    标签: silverlight xaml binding static


    【解决方案1】:

    如果只是绑定到集合的问题,不妨在 ViewModel 的构造函数中进行。进一步考虑使用 ObservableCollection,以防您的静态集合随时间发生变化。

    【讨论】:

      【解决方案2】:

      您只能绑定到非静态公共属性(而不是字段)。但是您可以为这些属性使用任何“载体”(因此您不必在 ViewModel 中拥有这些属性)。让我们看看...

      <Resources>
          <LocaleHelperWrapper x:Key="Wrapper"/>
      </Resources>
      
      <ComboBox ItemsSource="{Binding Path=FriendlyNames,
                                      Source={StaticResource Wrapper}}"/>
      

      以及包装代码:

      public class LocaleHelperWrapper
      {
          public Dictionary<string, string> FriendlyNames
          {
              get { return LocaleHelper.FriendlyNames; }
          }
      }
      

      [编辑]ComboBox 支持DisplayMemberPathSelectedValue。假设您想使用 ComboBox 选择 Key 并显示您 Dictionary 的 KeyValuePairsValue

      <ComboBox
          DisplayMemberPath="Value"
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=MySelectionViewModel.SelectedKey, Mode=TwoWay}"
          ItemsSource="..."/>
      

      【讨论】:

        猜你喜欢
        • 2013-03-23
        • 1970-01-01
        • 2011-03-08
        • 1970-01-01
        • 2015-01-17
        • 2012-02-04
        • 2012-03-10
        • 2021-10-03
        • 2016-12-12
        相关资源
        最近更新 更多