2016-03-30 13 views
0

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; 
+0

実際には、SelectedValueを使用できます。しかし実際にあなたのクラスであれば、eatherは明示的な変換を使用し、フィールド(YourDepartmentClass)departmentComboBox.SelectedItem.Nameを呼び出します。たとえば、 eatherはYourDepartmentClass.ToStringメソッドをオーバーライドし、departmentComboBox.SelectedItem.ToStringを使用します(Stringへの上書きは悪いオプションです) – Vladimir

+0

departmentComboBox.ItemSourceはどのように設定していますか? ItemSourceはComboBoxItemsを生成するために使用され、ComboBoxItems自体にアクセスするために使用することはできません。 – Donogst

+0

@Cbreezeありがとう、私は以下の答えを追加しました – Donogst

答えて

1

を:

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

あなたは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; 
    } 
} 
0

コンボボックスを作成するための文字列のリストをアイテムソースから作成しています。これはすばらしいです。混乱はそれらにアクセスする方法を超えています。 ItemSourceを再度使用すると、同じ文字列のリストが返され、選択した文字列と同じかどうかを確認しようとしています。選択した項目を取得するには、.SelectedItemプロパティを使用するのが一番良い方法です。最初にNullを確認してforループを削除することもできます:)

 if (departmentComboBox.SelectedItem != null) 
     { 
      criteria.Add(new Predicate<EmployeeModel>(x => x.Department == departmentComboBox.SelectedItem as string)); 
     } 
関連する問題