原文:[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. 当浏览器输入url的时候发生了什么

    当用户在浏览器地址栏里面输入一个url的时候.接下来会发生一系列的过程.首先是DNS解析, 将域名转换成对应的IP地址,之后浏览器与远程Web服务器通过TCP三次握手协商来建立一个TCP/IP连接.该 ...

  2. SSRS 请求并显示SharePoint人员和组字段

    场景: 使用Reporting Service请求SharePoint List,该list中包含人员和组字段.要求:只显示人员或组的display name.示例如下: 项目 参与人员 期望显示 项 ...

  3. haproxy nginx 多路径

    nginx 多路径: location / { root /t/deploy/zjdev/deployedApps/zjzc-web-frontEnd/; index index.html index ...

  4. bzoj1664 [Usaco2006 Open]County Fair Events 参加节日庆祝

    Description Farmer John has returned to the County Fair so he can attend the special events (concert ...

  5. 在Linux CentOS 6.5 (Final)上安装git-1.9.0

    CentOS 6.5 (Final)默认安装的git版本为1.7.1.3,而我们希望安装1.9.0版本.由于rpm安装库里没有1.9.0版本,因此我们需要找其它方法来安装. 网上有很多文章介绍了如何从 ...

  6. AutoResetEvent与ManualResetEvent区别

    本文来自:http://www.360doc.com/content/10/1126/10/3267996_72536817.shtml 在.Net多线程编程中,AutoResetEvent和Manu ...

  7. Android手机APN设置(中国移动 联通3G 电信天翼),解决不能上网的问题

    中国移动 第一步,设置CMNET上网 新建APN 1.名称:cmnet 2.APN:cmnet 3.APN类型:default 就仅仅填写上面3个选项,其它都是默认,不用填写. 第二步,设置彩信 新建 ...

  8. 通过ant脚本编译打包android工程

    通过ant脚本,编译打包android工程 1.Android程序编译.打包.签名.发布的三种方式:  方式一:命令行手动编译打包  方式二:使用ant自动编译打包  方式三:使用eclipse+AD ...

  9. winform —— 界面

    winform 界面简单介绍 窗体事件:理解为委托变量,指向哪个函数,就执行哪个函数.窗体:显示窗体的过程是一个通过模板造对象的过程.先走构造函数,构造函数中的InitializeComponent( ...

  10. 自定义view(自定义view的时候,三个构造函数各自的作用)

    package com.timeshare.tmband.Utils; import android.content.Context; import android.content.res.Typed ...