原文:[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. path类和directory类对文件的路径或目录进行操作

    Path: 对文件或目录的路径进行操作(很方便)[只是对字符串的操作] 1.目录和文件操作的命名控件System.IO    2.string Path.ChangeExtension(string ...

  2. 【待整理】IOS开发之下载

    一.传统的下载文件的方式 - (void)downloaderWithUrl:(NSURL *)url { NSURLRequest *request = [NSURLRequest requestW ...

  3. Oracle select 中case 的使用以及使用decode替换case

    表结构如下: 将money<50的显示为贫农,money<80的显示为中农,其他的显示为富农,sql 语句如下 select name, case then '贫农' then '中农' ...

  4. 《how to design programs》第10章表的进一步处理

    返回表的函数: 下面是一个求工资的函数: ;; wage : number  ->  number ;; to compute the total wage (at $12 per hour) ...

  5. 哥德尔,图灵和康托尔 part 1 哥德尔编号

    在看计算理论相关的书的时候,偶然看到这个blog,http://skibinsky.com/godel-turing-and-cantor-the-math/,写的很好.我觉得用自动机的方式讲计算理论 ...

  6. iOS 实时监听app的网络连接状态

    实际iOS开发中,在网络通信中我们大部分使用第三方(只谈短链),譬如 AFNetworking.ASIHttpRequest(这个停更了,想必现在没多少人用),swift的 Alamofire 等. ...

  7. Can you find it?(二分 二分+STL set map)

    Can you find it? Time Limit : 10000/3000ms (Java/Other)   Memory Limit : 32768/10000K (Java/Other) T ...

  8. 兼容各个浏览器的H.264播放: H.264+HTML5+FLOWPLAYER+WOWZA+RMTP

    一.方案确定 计划做视频播放,要求可以播放H264编码的mp4文件,各个浏览器,各种终端都能播放. 首先查找可行性方案, http://www.cnblogs.com/sink_cup/archive ...

  9. AS3聊天单行输入框图文混排完美实现

    几年前刚毕业.第一个游戏模块做的就是聊天.到如今.几个游戏写过几次聊天模块. 之前在4399做的<幻龙骑士>(又名<神骑士>),还有上周六刚上线的<疯狂的子弹>, ...

  10. GCC、GDB、Makefile

    1.GCC程序编译 Linux系统下的gcc(GNUCCompiler)是GNU推出的功能强大.性能优越的多平台编译器,是GNU的代表作之一.gcc可以在多种硬体平台上编译出可执行程序,其执行效率与一 ...