【问题标题】:Load data from dictionary in combobox从组合框中的字典加载数据
【发布时间】:2013-08-30 10:32:55
【问题描述】:

您好,我在 WPF 中有组合框

<ComboBox Name="mcombo" SelectedValuePath="Key" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=dictionary}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

我也落后了

Dictionary<string, string> dictionary = new Dictionary<string, string>();
        dictionary.Add("val", "valvalval"); 

我忘记了什么?在组合框中,没有数据!

【问题讨论】:

  • datacontext 设置正确?
  • 如何制作datacontex?

标签: c# wpf dictionary combobox


【解决方案1】:

首先字典应该是属性而不是变量。

那么你应该将 Dictionary 绑定到 ItemsSource

<ComboBox Name="mcombo" SelectedValuePath="Key" ItemsSource="{Binding Dictionary}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Value}" /> /Dont bind dictionary here. makes no sense
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

希望这会有所帮助..

谢谢

【讨论】:

  • 当我添加:mcombo.datacontext = dictionary;
  • 我的程序报错:调用目标抛出异常。
  • 使用 mcombo.ItemsSource= 字典;(但你不再需要绑定)。如果要使用 mvvm,则必须创建字典类型的属性,而不是变量。
  • 如果您正在执行 mcombo.datacontext = dictionary,理想情况下您不应该这样做,您必须将 ItemsSource 绑定更新为仅 ItemsSource="{Binding}"。看看这是否适合你。如果可能的话,你可以发布你得到的异常
猜你喜欢
  • 1970-01-01
  • 2015-06-30
  • 2021-04-03
  • 2016-02-04
  • 1970-01-01
  • 2015-07-25
  • 2022-01-21
  • 2020-12-23
  • 1970-01-01
相关资源
最近更新 更多