我想要一个这样的组合框:
但是在代码中没有办法做到这一点。我正在使用 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/