WPF中ComboBox搭配IValueConverter修改背景色取值异常如何解决
问题根源
你拿到的value是ComboBoxItem控件对象而非其显示的文本,直接调用ToString()会输出控件类型+内容的拼接字符串,自然无法匹配。
方案1:修改XAML(更推荐,符合MVVM设计规范)
只需要给ComboBox添加SelectedValuePath="Content"属性,指定选中值取ComboBoxItem的Content属性(也就是你写的Male/Female字符串),不需要改动转换器代码:
<ComboBox SelectedValue="{Binding Gender, Mode=TwoWay}" SelectedValuePath="Content"> <ComboBoxItem>Male</ComboBoxItem> <ComboBoxItem>Female</ComboBoxItem> </ComboBox>
也可以直接用字符串作为ComboBox的项,省去显式声明ComboBoxItem的步骤,需要先引入System命名空间:
<!-- 先在Window的属性里加sys命名空间声明 --> xmlns:sys="clr-namespace:System;assembly=mscorlib" <!-- ComboBox写法改为 --> <ComboBox SelectedItem="{Binding Gender, Mode=TwoWay}"> <sys:String>Male</sys:String> <sys:String>Female</sys:String> </ComboBox>
方案2:修改转换器代码
如果不想改XAML,可以在转换器里先把value转换为ComboBoxItem类型,再取其Content属性做判断:
using System.Windows.Controls; // 需要引入ComboBoxItem的命名空间 public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(value is ComboBoxItem comboItem) { string gender = comboItem.Content?.ToString(); if (gender == "Male") { return new SolidColorBrush(Color.FromArgb(255, 27, 161, 226)); } else if (gender == "Female") { return new SolidColorBrush(Color.FromArgb(255, 216, 0, 115)); } } // 可以返回默认背景色代替null return Brushes.White; }
内容的提问来源于stack exchange,提问作者StephenH
相关产品推荐
相关产品推荐

