在ComboBox上筛选选定项目作为字符串

时间:2016-03-30 10:20:25

标签: c# wpf combobox tostring

我正在尝试使用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.Department的类型为string。如何正确访问SelectedItem以便我可以正确使用我的过滤方法?

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

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

3 个答案:

答案 0 :(得分:2)

你可以这样试试:

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;}
}

答案 1 :(得分:1)

您可以使用ToString()的{​​{1}}方法。

SelectedItem

确保组合框的项目中没有foreach (ComboBoxItem cItem in departmentComboBox.ItemsSource) { if (departmentComboBox.SelectedItem != null) { criteria.Add(new Predicate<EmployeeModel>(x => x.Department == departmentComboBox.SelectedItem.ToString())); break; } } 值,否则您可以使用以下代码:

null

答案 2 :(得分:0)

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

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