DataGrid
でフィルタリングするためにComboBox.SelectedItem
を使用しようとしていますが、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
に正しくアクセスして、フィルタリング方法で正しく使用できるようにするにはどうすればよいですか?
EDIT:ComboBoxアイテムの追加方法を示します。
List<string> distinctList = Employees.Select(i => i.Department).Distinct().ToList();
distinctList.Insert(0, "Everyone");
distinctList.Sort();
departmentComboBox.ItemsSource = distinctList;
実際には、SelectedValueを使用できます。しかし実際にあなたのクラスであれば、eatherは明示的な変換を使用し、フィールド(YourDepartmentClass)departmentComboBox.SelectedItem.Nameを呼び出します。たとえば、 eatherはYourDepartmentClass.ToStringメソッドをオーバーライドし、departmentComboBox.SelectedItem.ToStringを使用します(Stringへの上書きは悪いオプションです) – Vladimir
departmentComboBox.ItemSourceはどのように設定していますか? ItemSourceはComboBoxItemsを生成するために使用され、ComboBoxItems自体にアクセスするために使用することはできません。 – Donogst
@Cbreezeありがとう、私は以下の答えを追加しました – Donogst