【发布时间】:2015-03-28 03:34:35
【问题描述】:
我想学习 WPF 编程。 我想知道将员工的性别绑定到 ComboBox:
class Staff {
public int Gender {get; set;}
}
class ViewModel {
private Staff _staff
public Staff Staff {
get {return _staff;}
set {
_staff = value;
RaisePropertyChangedEvent("Staff");
}
}
}
<ComboBox SelectedItem="{Binding Staff.Gender, Converter={StaticResource GenderConverter}}">
<ComboBoxItem IsSelected="True" Content="{StaticResource strGenderMale}"/>
<ComboBoxItem Content="{StaticResource strGenderFemale}"/>
<ComboBoxItem Content="{StaticResource strGenderOther}"/>
</ComboBox>
GenderConverter 是我自定义的转换器,用于转换 int 字符串(0:男,1:女,2:其他)
public class IntegerToGenderConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value is int) {
if ((int)value == MyConstants.GENDER_MALE) { //GENDER_MALE is 1
return MyConstants.GENDER_MALE_STR; //GENDER_MALE_STR is the string: "Male"
}
if ((int)value == MyConstants.GENDER_FEMALE) {
return MyConstants.GENDER_FEMALE_STR;
}
}
return MyConstants.GENDER_OTHER_STR;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
switch (value.ToString()) {
case MyConstants.GENDER_MALE_STR:
return MyConstants.GENDER_MALE;
case MyConstants.GENDER_FEMALE_STR:
return MyConstants.GENDER_FEMALE;
default:
return MyConstants.GENDER_OTHER;
}
}
}
当我运行应用程序时,员工不为空(其他所有内容(例如姓名,出生日期......)都绑定得很好,除了性别:(
编辑:
当我创建一个 List Genders 并将其绑定到 ComboBox 的属性 ItemsSource 而不是使用标签时,它运行良好。为什么???
【问题讨论】:
-
当我创建了一个 List
Genders 并将其绑定到 ComboBox 的属性 ItemsSource 而不是使用 标记时,它运行良好。为什么??? -
你能粘贴你的完整代码吗
标签: c# wpf xaml data-binding combobox