将 ComboBox 选定项过滤为字符串

Filter on ComboBox Selected Item as String

我正在尝试使用 ComboBox.SelectedItem 过滤 DataGrid,但是我在访问 SelectedItem 作为 string 时遇到问题。这是我迄今为止尝试过的;

foreach (ComboBoxItem cItem in departmentComboBox.ItemsSource)
{
    if (departmentComboBox.SelectedItem != null)
    {
        criteria.Add(new Predicate<EmployeeModel>(x => x.Department == departmentComboBox.SelectedItem as string));
        break;
    }
}

这导致异常;

Additional information: Unable to cast object of type 'System.String' to type 'System.Windows.Controls.ComboBoxItem'.

x.Departmentstring 类型。我怎样才能正确访问 SelectedItem 以便我可以在我的过滤方法中正确使用它?

编辑:显示如何添加 ComboBox 项目;

List<string> distinctList = Employees.Select(i => i.Department).Distinct().ToList();
distinctList.Insert(0, "Everyone");
distinctList.Sort();
departmentComboBox.ItemsSource = distinctList;

您可以使用 SelectedItemToString() 方法。

foreach (ComboBoxItem cItem in departmentComboBox.ItemsSource)
{
    if (departmentComboBox.SelectedItem != null)
    {
        criteria.Add(new Predicate<EmployeeModel>(x => x.Department == departmentComboBox.SelectedItem.ToString()));
        break;
    }
}

确保组合框的项目中没有null值,否则您可以使用以下代码:

foreach (ComboBoxItem cItem in departmentComboBox.ItemsSource)
{
    if (departmentComboBox.SelectedItem != null)
    {
        criteria.Add(new Predicate<EmployeeModel>(x => x.Department == "" + departmentComboBox.SelectedItem));
        break;
    }
}

你可以这样试试:

foreach (ComboBoxItem cItem in departmentComboBox.ItemsSource){
if (departmentComboBox.SelectedItem != null)
{
    string selectedItemName = this.departmentComboBox.GetItemText(this.departmentComboBox.SelectedItem);
    criteria.Add(new Predicate<EmployeeModel>(x => x.Department.Equals(selectedItemName)));
    break;}
}

您正在通过项目源创建一个字符串列表来填充组合框,这很好,但混淆的是如何访问它们。再次使用 ItemSource 将返回相同的字符串列表,然后您将尝试检查每个字符串是否与所选字符串相同。获取所选项目的更好方法是通过 .SelectedItem 属性。首先检查 Null,你也可以放弃 for 循环 :)

        if (departmentComboBox.SelectedItem != null)
        {
            criteria.Add(new Predicate<EmployeeModel>(x => x.Department == departmentComboBox.SelectedItem as string));
        }