我正试图使用ComboBox.SelectedItem
在DataGrid
上进行筛选,但我在作为string
访问SelectedItem
时遇到问题。这就是我迄今为止所尝试的;
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'.
CCD_ 5属于CCD_。如何正确访问SelectedItem
,以便在筛选方法中正确使用它?
编辑:显示如何添加组合框项目;
List<string> distinctList = Employees.Select(i => i.Department).Distinct().ToList();
distinctList.Insert(0, "Everyone");
distinctList.Sort();
departmentComboBox.ItemsSource = distinctList;
您可以这样尝试:
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;}
}
您可以使用SelectedItem
的ToString()
方法。
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;
}
}
您正在通过项源创建一个字符串列表来填充组合框,这很好,但困惑在于如何访问它们。再次使用ItemSource将返回相同的字符串列表,然后您将尝试检查每个字符串是否与所选字符串相同。获取所选项目的更好方法是通过.SelectedItem属性。首先检查Null,你也可以放弃for循环:)
if (departmentComboBox.SelectedItem != null)
{
criteria.Add(new Predicate<EmployeeModel>(x => x.Department == departmentComboBox.SelectedItem as string));
}