【问题标题】:Binding a Dictionary to a Combobox in WPF displays incorrectly将字典绑定到 WPF 中的组合框显示不正确
【发布时间】:2014-04-01 22:50:44
【问题描述】:

已解决 - 主题干扰了显示

这是我第一次使用 WPF,所以可能有一个明显的答案。

我正在尝试显示月份选择组合框,其中显示月份名称,并且在进行选择时捕获整数值。

XAML

<ComboBox Margin="5" IsEditable="False" 
         IsEnabled="{Binding IsCompanyFileUploadPeriodEnabled}" 
         ItemsSource="{Binding StartMonths}" 
         DisplayMemberPath="Key" 
         SelectedValuePath="Value" 
         SelectedValue="{Binding SelectedStartMonthID}" 
         Width="50"></ComboBox>

编辑: ViewModel 扩展了 Galasoft MvvmLight ViewModelBase,它提供了 RaisePropertyChanged 方法。

视图模型

Dictionary<string, int> _startMonths;
public Dictionary<string, int> StartMonths
{
    get
    {
        if (_startMonths == null)
        {
            _startMonths = new Dictionary<string, int>();
            for (int i = 1; i < 13; i++)
            {
                _startMonths.Add(System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(i),
                    i);
            }
        }
        return _startMonths;
    }
}

int _selectedStartMonthID;
public int SelectedStartMonthID
{
    get
    {
        return _selectedStartMonthID;
    }
    set
    {
        _selectedStartMonthID = value;
        RaisePropertyChanged(() => SelectedStartMonthID);
    }
}

但由于某种原因,当我运行应用程序时,组合框显示为

  • [1 月 1 日]
  • [2 月 2 日]

有谁知道为什么它可能会忽略 DisplayMemberPath 指令?选择元素时,SelectedValuePath 设置似乎工作正常。

【问题讨论】:

  • 如果您仍然会看到错误的值,最好尝试 FallbackValue - 'WrongBinding' - 它必须是其他东西,而不是绑定。
  • 我可以理解为什么您希望在动态数据的情况下回退,但这是月份名称和值的静态列表。它应该每次都绑定......
  • @FodderZone - 它只会在第一次加载时初始化。如果它之前被调用过,私有变量将不会为空并且不会调用该代码。
  • 您确定您没有应用任何不在此处的样式吗?我完全复制了您的代码,并且只有月份名称显示在 ComboBox 中。
  • 不知道为什么你会得到 ,1 ,2。但我会把整数作为键。

标签: c# wpf xaml mvvm


【解决方案1】:

ComboBox DisplayMemberPath 绑定被 Themes BureauBlue 和 WhistlerBlue 破坏

http://wpf.codeplex.com/workitem/10129

【讨论】:

  • 太好了,在 Windows 10 VS 2017 中似乎仍然很糟糕。我认为我在任何地方都没有蓝。知道该怎么做吗?
  • 对不起,自从提出这个问题以来,我还没有接触过 WPF。我建议检查更改主题是否有帮助。也许链接中发布的建议修复会有所帮助?
【解决方案2】:

看看 StringFormat。

MSDN StringFormat

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2018-12-26
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多