2013-05-28 72 views
2

我在XAML中有一個ComboBoxC# - WPF組合框的SelectedValue從枚舉

<ComboBox x:Name="Form1Combobox" Width="150" IsSynchronizedWithCurrentItem="True" SelectedValue="{Binding Dept}" ItemsSource="{Binding Source={StaticResource ResourceKey=Depts}}"/> 

我是使用ObjectDataProvider從枚舉填充ComboBox與價值的靜態資源:

public enum Department 
{ 
    Leadership, 
    Maintenance, 
    Salaried, 
    Commission 
} 

我有員工的ObservableCollection,我將他們的部門財產設置爲某種(例如,Dept = Department.Leadership)。僱員類別使用INotifyPropertyChange,其他事物包括姓名。 ComboBox填充正確,但它的初始值未被設置。

我的問題是,我如何將ComboBoxSelectedValue設置爲員工的適當屬性?

編輯: 這是我觀察到的集合(片段)。

ObservableCollection<Employee> emps = new ObservableCollection<Employee> 
{ 
    new Employee{Name = "Exam Pell", Title = "Manager", Phone = "(801) 555-2677", Email = "[email protected]", isActive = true, Dept = Department.Commission}, 
}; 

這是我的靜態資源:

<ObjectDataProvider x:Key="Depts" MethodName="GetValues" ObjectType="{x:Type sys:Enum}"> 
    <ObjectDataProvider.MethodParameters> 
     <x:Type TypeName="en:department+Department"></x:Type> 
    </ObjectDataProvider.MethodParameters> 
</ObjectDataProvider> 

其實我已經注意到,每當我嘗試設置的SelectedValue或selectedItem,組合框變爲紅色(我有一個DataGridComboBoxColumn,它也依賴於這一點,但有一個ItemsSource)。此外,我還有一個ListBox也顯示部門 - 但是,這一個顯示正確,但不更新,即使我更改任何員工的ComboBox選擇。

回答

3

而不是設置SelectedValue的設置SelectedItem

要設置SelectedValue您需要設置DisplayMemberPathValueMemberPath。在你的情況下,因爲它是一個枚舉,你不能設置它們。

所以設置SelectedItem這樣

<ComboBox x:Name="Form1Combobox" 
      Width="150" 
      IsSynchronizedWithCurrentItem="True" 
      SelectedItem="{Binding Dept}" 
      ItemsSource="{Binding Source={StaticResource ResourceKey=Depts}}"/> 
+0

出於某種原因,這是行不通的。我可以循環使用不同的員工,但組合框不會改變;它總是顯示最後選擇的值。此外,當我嘗試更改某個員工的值時,組合框邊框變爲紅色,直到我切換到其他員工(值保持不變,但紅色邊框消失)。 – Carlos

+0

顯示「Depts」的聲明以及如何填寫它? –

+0

我希望有所幫助 – Carlos