c# - 如何在通用组合框中添加更多选项

标签 c# wpf mvvm

我想要一个这样的组合框:

enter image description here

但是在代码中没有办法做到这一点。我正在使用 MVVM 模式。所以我有一个看法:

<ComboBox Style="{StaticResource ComboStyle}" ItemsSource="{Binding ResultObjects}" SelectedItem="{Binding SelectedObject,Mode=TwoWay}" />

和 View 模型:
public IEnumerable<DateTime> ResultObjects { get;set; }
public DateTime SelectedObject{ get;set; }

事实是 -All- 和 -custom- 不是 DateTime。它不能被添加到这个列表中。
我记得在 MVC 中我们有一个“下拉助手”。

我可以在 MVVM 中做什么?

最佳答案

您可以绑定(bind)到 IEnumerable<KeyValuePair<DateTime?, string>>其中键表示实际值,值表示该值的自定义字符串表示:

public IEnumerable<KeyValuePair<DateTime?, string>> ResultObjects { get; set; }
public DateTime? SelectedObject { get; set; }

...

ResultObjects = new List<KeyValuePair<DateTime?, string>>()
{
    new KeyValuePair<DateTime?, string>(null, "All"),
    new KeyValuePair<DateTime?, string>(new DateTime(2018,04,17), new DateTime(2018,04,17).ToString("yyyy/MM/dd")),
    new KeyValuePair<DateTime?, string>(new DateTime(2018,04,17), new DateTime(2018,04,17).ToString("yyyy/MM/dd @ HH:mm:ss")),
    new KeyValuePair<DateTime?, string>(new DateTime(2018,04,17), "Custom...")
};
...

XAML:
<ComboBox 
    ItemsSource="{Binding ResultObjects}" 
    SelectedValue="{Binding SelectedObject}"
    DisplayMemberPath="Value"
    SelectedValuePath="Key"/>

显然,除了实际的 DateTime 之外,您无法返回任何内容来自 IEnumerable<DateTime> 的值如果您还希望能够表示其他类型的值,那么您应该更改源集合的类型。

关于c# - 如何在通用组合框中添加更多选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858306/

相关文章:

WPF TabControl 更改选定的选项卡

c# - DispatcherTimer 的绑定(bind)不在 View 上显示它的值

c# - 当我运行 WPF MVVM 应用程序时,显示主窗口的两个实例

silverlight - MVVM 灯 - 如何访问其他 View 模型中的属性

mvvm - 如何避免在我的 ViewModel 中查看特定代码

c# - 如何在.NET中获取磁盘的分区UUID

c# - 如何使用 C# 从 ASP.Net 中的数据库中获取最新记录?

c# - 在Web和控制台应用程序之间共享配置文件

c# - 如何使用带有 stackexchange.redis 库的 ZSCAN 命令获取游标和分页的结果?

wpf - Powerbuilder .net、MVVM 和单元测试