原文: [WPF 如何] 如何向 ComboBox 添加一个空白选项

看到这个问题,你可能会蔑视一笑 : 这也能成文章?

确实,你只需要在 ItemsSource 的0位置上插入一个空白的项就是了,如:

1                 this.Accounts = rep.All.OrderBy(a => a.Account).Select(a => a.Account).ToList();
2                 this.Accounts.Insert(0, "");

1 <ComboBox Grid.Column="3" Grid.Row="2" x:Name="Accounts" SelectedItem="{Binding SelectedAccount}" />

确实够简单,表现的很完美.

换成可空的数据源呢?

 1         public static List<LogisticsTypes?> DeliveryTypes {
 2             get;
 3             set;
 4         }
 5
 6
 7         public LogisticsTypes? SelectedDeliveryType {
 8             get;
 9             set;
10         }

DeliveryTypes = Enum.GetValues(typeof(LogisticsTypes)).Cast<LogisticsTypes?>().ToList();
DeliveryTypes.Insert(0, null);

1 <ComboBox Grid.Row="1" Grid.Column="5" ItemsSource="{Binding Source={x:Static model:OrderQueryViewModel.DeliveryTypes}}" SelectedItem="{Binding SelectedDeliveryType,Mode=TwoWay}">
2                     <ComboBox.ItemTemplate>
3                         <DataTemplate>
4                                 <TextBlock Text="{Binding . , Converter={StaticResource EnumDesc}}" />
5                         </DataTemplate>
6                     </ComboBox.ItemTemplate>
7                 </ComboBox>

这样写很美完美啊!有什么不对劲吗?如果你说:对,很完美,那就该我蔑视你了!

没有实践就没有"发盐权", 本文就是说的这个东西.

上面的写法看似很好,可是: 插入的空白项不能通过鼠标选择! 只能通过键盘才能选择.

具体为什么, 我也说不出来个所以然来, 见招拆招,见庙拆庙而以, 不遇上它,我也不知道会有这一马事.

说了这么多废话,到底有没有解决办法呢?

我试了 TargetNullValue, FallbackValue , 不过这两个东西是为了解决显示文本的问题的(不知道说的对不对),不信你可以试试, 它们跟本就没用,依然无法用鼠标去选择.

用 CompositeCollection 混合集合

 1                 <ComboBox Grid.Row="1" Grid.Column="5" SelectedItem="{Binding SelectedDeliveryType}">
 2                     <ComboBox.ItemsSource>
 3                         <CompositeCollection>
 4                             <ComboBoxItem Content="" />
 5                             <CollectionContainer Collection="{Binding Source={x:Static model:OrderQueryViewModel.DeliveryTypes}}" />
 6                         </CompositeCollection>
 7                     </ComboBox.ItemsSource>
 8                     <ComboBox.ItemTemplate>
 9                         <DataTemplate>
10                             <TextBlock Text="{Binding . , Converter={StaticResource EnumDesc}}" />
11                         </DataTemplate>
12                     </ComboBox.ItemTemplate>
13                 </ComboBox>

嗯, 这下可以选择空白项了.

只是选择了空白项后, 接着还有问题 :  选择空白项的时候,是不是会有个 红框框 框住了这个 ComboBox ? 像这样:

为什么呢? 看到 SelectedItem 了没有? 选择的空白选项是个 ComboBoxItem

System.Windows.Data Error: 23 : Cannot convert 'System.Windows.Controls.ComboBoxItem' from type 'ComboBoxItem' to type 'System.Nullable`1[AsNum.Aliexpress.Entity.LogisticsTypes]' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: EnumConverter 无法从 System.Windows.Controls.ComboBoxItem 转换。
在 System.ComponentModel.TypeConverter.GetConvertFromException(Object value)
在 System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
在 System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
在 System.ComponentModel.NullableConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
在 MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'
System.Windows.Data Error: 7 : ConvertBack cannot convert value 'System.Windows.Controls.ComboBoxItem' (type 'ComboBoxItem'). BindingExpression:Path=SelectedDeliveryType; DataItem='OrderQueryViewModel' (HashCode=10859455); target element is 'ComboBox' (Name=''); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: EnumConverter 无法从 System.Windows.Controls.ComboBoxItem 转换。
在 MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)
在 MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
在 System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

是的, 转换为 SelectedItem 的时候失败了.

疙瘩,一波未平一波又起. 是用 CompositeCollection 还是用 Insert ? 一个不能选择空白项, 一个可以选, 但是选了也白选.

纠结,郁闷,没人可以问, 我劝你牙的就别百度了, 百了也没用 (好像根本就没有相关的文章是中文的!这不能愿百度).

搜英文?怎么组织关键词? 算鸟, 即然这样,就换个角度吧. 用 Insert 铁定不行(别喷我噢,我确实没有找出来可行的办法), 用 CompositeCollection 很接近解决办法了,只是转换的时候出了点小问题而以,不行就加个 Converter 呗.

记住一句话:不动手就没发盐权

 1     public class CanNullConverter : IValueConverter {
 2         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
 3             return value;
 4         }
 5
 6         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
 7             NullableConverter nullableConvert;
 8             var toType = targetType;
 9             if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
10                 nullableConvert = new NullableConverter(targetType);
11                 toType = nullableConvert.UnderlyingType;
12             }
13
14             return value.GetType().Equals(toType) ? value : null;
15         }
16     }

<ac:CanNullConverter x:Key="CanNull" />
....
....
....
<ComboBox Grid.Row="1" Grid.Column="5" SelectedItem="{Binding SelectedDeliveryType, Converter={StaticResource CanNull}}">

一切不变,就是在 绑定 SelectedItem 的时候,加了一个 CanNullConverter 这个东西.

好拉,就这些.

谢谢围观.

[WPF 如何] 如何向 ComboBox 添加一个空白选项相关推荐

  1. python选择框_python - 自定义/删除Django选择框空白选项

    python - 自定义/删除Django选择框空白选项 我正在使用Django 1.0.2. 我写了一个由Model支持的ModelForm. 此模型有一个ForeignKey,其中blank = ...

  2. 网站添加自己公司的地图(使用的百度地图)时只显示一个空白框

    最近维护公司网站时在添加地图出问题了,按照http://api.map.baidu.com/lbsapi/creatmap/网址上制作后复制代码,然后添加到我想弄的位置后显示不出来,只显示了一个空白的 ...

  3. el-upload回显细节--没有图片数据返回的时候每点击一次添加多了一个空白图片

    如果没有图片,就会自动赋值一个空的值给这个数组,就会出现一个空白的照片,每点击一次就添加一个,肯定有个地方有问题,一起来看看 那是因为回显的时候做了初始化,没有进行判断是否有值再添加. imgInit ...

  4. 【IntelliJ IDEA】添加一个新的tomcat,tomcat启动无法访问欢迎页面,空白页,404

    ===================================第一部分,添加一个tomcat================================================== ...

  5. 为WPF和Silverlight的Grid添加边框线(zz)

    Grid是WPF和Silverlight中的一个重要的布局元素,其他的布局元素还有StackPanel, Canvas, Border等等.从字面上说,Grid是一个表格的意思,它的使用也确实很方便, ...

  6. 为WPF和Silverlight的Grid添加边框线

    Grid是WPF和Silverlight中的一个重要的布局元素,其他的布局元素还有StackPanel, Canvas, Border等等.从字面上说,Grid是一个表格的意思,它的使用也确实很方便, ...

  7. WPF整理-为User Control添加依赖属性

    WPF整理-为User Control添加依赖属性 原文:WPF整理-为User Control添加依赖属性 依赖属性 ".NET properties are nothing more t ...

  8. OD反汇编EXE添加一个启动时的消息框

    OD反汇编EXE添加一个启动时的消息框 最近有一个要修改PE文件的需求,就先从EXE文件下手吧,我也是初学一个小时而已,不过之前接触过一点汇编罢了,这篇文章算是个DEMO,主要的思路是将其反汇编得到汇 ...

  9. 微信小程序创建一个空白页面

    小程序创建一个空白页面还是比较简单的. pages文件夹下就是一个个页面组件 想要新增页面组件则找到app.json里面的pages数组,然后添加一组数据即可得到一个页面组件了. 然后就会生成一堆文件 ...

最新文章

  1. 数据中心、智慧机房全套解决方案
  2. linux路由表命令
  3. C++的Android接口---配置NDK
  4. 精通ASP.NET MVC ——路由
  5. 温度记录仪开发_TinkerNode NBIoT物联网开发板
  6. Codeforces Round #510 (Div. 2) AB By cellur925
  7. 数据结构视频教程 -《[猎豹网校]数据结构与算法_C语言》
  8. 《微信小程序进阶实战之分答应用开发(中级项目)》(完整版)
  9. HTML5的结构元素
  10. 美团实习生电面之谈(成功拿到offer)
  11. 炸场!通用人工智能最新突破:一个模型、一套权重通吃600+视觉文本和决策任务,DeepMind两年研究一朝公开...
  12. php 百度地图根据经纬度获取地址,百度地图 根据经纬度获取地址
  13. installShield_script学习
  14. html依次显示选中的值,html 快速布局 - osc_pw143nru的个人空间 - OSCHINA - 中文开源技术交流社区...
  15. 全屏播放PPT时,播放音乐
  16. [R]提高R语言速度
  17. WV.21-大数阶乘算法1-序
  18. 和优秀的人在一起,会激励自己变得优秀。
  19. 计算机课程基础常用,计算机基础课程实用标准
  20. 【我的OpenGL学习进阶之旅】关于OpenGL ES 开启深度测试,直接黑屏的问题的解决方法

热门文章

  1. 微信开发必备工具:利用cpolar在公网上测试本地Web网站或移动应用程序
  2. android 开游艇游戏,游艇狂飙游戏-游艇狂飙安卓版预约_第一手游网
  3. Gps测量两点之间的距离
  4. 讯时网关路由规则小结
  5. 各类编程视频教学资源下载
  6. 系统学习——Bootstrap
  7. oracle 在此 select 语句中缺少 into 子句,Go database/sql文档
  8. A pseudo attribute name is expected.解决方法
  9. 再见PDF提取收费!我用100行Python代码搞定!去你的收费!
  10. Android图形shape的gradient渐变色背景