【问题标题】:WPF ComboboxItem bindingWPF ComboboxItem 绑定
【发布时间】: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


【解决方案1】:

当您像这样显式添加它们时,ComboBox 使用 ComboBoxItem 作为项目类型

<ComboBox>
    <ComboBoxItem Content="..."/>
    ...
</ComboBox>

这意味着SelectedItem 属性返回一个ComboBoxItem,然后将其传递给您的转换器。但是,您的转换器不需要 ComboBoxItem 类型的值。

当您添加整数时 - 就像在绑定的性别列表中一样 - 项目类型是 int,您在转换器中成功处理了它。在这种情况下,ComboBox 类仅在内部创建和使用 ComboBoxItems。

这是派生自 ItemSource 的所有 WPF 控件中的常见行为。他们使用用户提供的项目类型。


也就是说,您通常会为您的 Gender 属性使用枚举类型:

public enum Gender
{
    Male, Female, Other
}

public class Staff
{
    public Gender Gender { get; set; }
}

然后您将 Gender 值添加到您的 ComboBox 并在没有转换器的情况下绑定 SelectedItem:

<ComboBox SelectedItem="{Binding Staff.Gender}">
    <local:Gender>Male</local:Gender>
    <local:Gender>Female</local:Gender>
    <local:Gender>Other</local:Gender>
</ComboBox>

其中local 是包含Gender 类型的C# 命名空间的XAML 命名空间声明。

【讨论】:

  • 感谢您的帮助。根据您的回复,我将尝试使用 而不是
猜你喜欢
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多