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

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

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

                 this.Accounts = rep.All.OrderBy(a => a.Account).Select(a => a.Account).ToList();
this.Accounts.Insert(, "");
 <ComboBox Grid.Column="3" Grid.Row="2" x:Name="Accounts" SelectedItem="{Binding SelectedAccount}" />

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

换成可空的数据源呢?

         public static List<LogisticsTypes?> DeliveryTypes {
get;
set;
} public LogisticsTypes? SelectedDeliveryType {
get;
set;
}
DeliveryTypes = Enum.GetValues(typeof(LogisticsTypes)).Cast<LogisticsTypes?>().ToList();
DeliveryTypes.Insert(0, null);
 <ComboBox Grid.Row="1" Grid.Column="5" ItemsSource="{Binding Source={x:Static model:OrderQueryViewModel.DeliveryTypes}}" SelectedItem="{Binding SelectedDeliveryType,Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding . , Converter={StaticResource EnumDesc}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

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

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

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

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

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

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

用 CompositeCollection 混合集合

                 <ComboBox Grid.Row="1" Grid.Column="5" SelectedItem="{Binding SelectedDeliveryType}">
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="" />
<CollectionContainer Collection="{Binding Source={x:Static model:OrderQueryViewModel.DeliveryTypes}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding . , Converter={StaticResource EnumDesc}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</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 呗.

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

     public class CanNullConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return value;
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
NullableConverter nullableConvert;
var toType = targetType;
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
nullableConvert = new NullableConverter(targetType);
toType = nullableConvert.UnderlyingType;
} return value.GetType().Equals(toType) ? value : null;
}
}
<ac:CanNullConverter x:Key="CanNull" />
....
....
....
<ComboBox Grid.Row="1" Grid.Column="5" SelectedItem="{Binding SelectedDeliveryType, Converter={StaticResource CanNull}}">

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

好拉,就这些.

谢谢围观.

[WPF 如何] 如何向 ComboBox 添加一个空白选项的更多相关文章

  1. DropDownList如何添加一个空白的选项

    ddl_class.Items.Insert(0,new ListItem("",""));

  2. angular中的 input select 值绑定无效,以及多出一个空白选项问题

    问题: <!-- 问题标签 --> <select ng-model="sortType"> <option value="1"& ...

  3. autoconf添加gcc调试选项

      autoconf生成的编译选项默认是"-g -O2".这个"-g"选项将我迷惑了,以为生成了GDB调试所需的信息,所以也就没有管后面的"-O2“选 ...

  4. easyUI combobox 添加空白项

    今天测试反馈了一个问题,希望可以在下拉框下面加一个空白的选项(下拉框用的是combobox方法). 开始分析这个问题: 首先,这个数据都是后台读出来的,那么我在后台直接添加可以么,答案是可以的,如果没 ...

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

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

  6. WPF dataGrid下的ComboBox的绑定

    WPF dataGrid下的ComboBox的绑定 Wpf中dataGrid中的某列是comboBox解决这个问题费了不少时间,不废话了直接上代码 xaml 代码 <DataGridTempla ...

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

    依赖属性 ".NET properties are nothing more than syntactic sugar over set and get methods." 我们知 ...

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

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

  9. WPF中DataGrid的ComboBox的简单绑定方式(绝对简单)

    在写次文前先不得不说下网上的其他wpf的DataGrid绑定ComboBox的方式,看了之后真是让人欲仙欲死. 首先告诉你一大堆的模型,一大堆的控件模板,其实或许你紧紧只想知道怎么让combobox怎 ...

随机推荐

  1. (转)使用scp命令在linux操作系统之间传递文件

    一.关于scp scp是英文secure copy (remote file copy program)的简称,主要用于在两台主机之间通过网络拷贝文件.scp使用ssh协议进行数据传递,其认证方式和安 ...

  2. 微软的OneDrive研究~

    Dropbox 很好,唯一觉得不爽的是只能同步指定的目录.不过被墙之后就不那么方便了,所以改用微软的 Live Mesh,缺点是支持的设备少(仅 PC 和 Mac). https://technet. ...

  3. 在线程中建立Form遇到的问题

    一个项目由很多Form组成,默认情况下在启动程序时,这些form都会被建立,这会黑屏很长时间,一种方法是用到Form时再建立,结果又发现如果Form设计复杂,建立的过程也会超过1秒以上,于是想到用线程 ...

  4. Windows搭建Sublime Text 3 + Go开发环境

    1. 安装Sublime Text 3 Sublime Text 3(以下简称ST)的下载与安装我就不说啦,目前还是一个测试版,不过据说比ST2增加了好多新功能,下载地址: http://www.su ...

  5. mysql logstash 配置

    [elk@dr-mysql01 mysql]$ cat logstash_mysql.conf input { file { type => "zj_mysql" path ...

  6. Linux系统编程(16)——正则表达式入门

    字符是计算机软件处理文字时最基本的单位,可能是字母,数字,标点符号,空格,换行符,汉字等等.字符串是0个或更多个字符的序列.文本也就是文字,字符串.说某个字符串匹配某个正则表达式,通常是指这个字符串里 ...

  7. Linux系统编程(6)——文件系统

    计算机的文件系统是一种存储和组织计算机数据的方法,它使得对其访问和查找变得容易,文件系统使用文件和树形目录的抽象逻辑概念代替了硬盘和光盘等物理设备使用数据块的概念,用户使用文件系统来保存数据不必关心数 ...

  8. COM组件开发实践(七)---多线程ActiveX控件和自动调整ActiveX控件大小(上)

    声明:本文代码基于CodeProject的文章<A Complete ActiveX Web Control Tutorial>修改而来,因此同样遵循Code Project Open L ...

  9. cf479C Exams

    C. Exams time limit per test 1 second memory limit per test 256 megabytes input standard input outpu ...

  10. 使用sp_configure启用 'Ad Hoc Distributed Queries'

    使用sp_configure启用 'Ad Hoc Distributed Queries' 原文地址:http://blog.sina.com.cn/s/blog_531bb7630100xh88.h ...