Reputation: 105
I have a ComboBox
in XAML:
<ComboBox x:Name="Form1Combobox" Width="150" IsSynchronizedWithCurrentItem="True" SelectedValue="{Binding Dept}" ItemsSource="{Binding Source={StaticResource ResourceKey=Depts}}"/>
My static resource is using an ObjectDataProvider
to populate the ComboBox
with values from an enum:
public enum Department
{
Leadership,
Maintenance,
Salaried,
Commission
}
I have an ObservableCollection
of employees, where I set their Dept property to something (say, Dept = Department.Leadership
). The employee class uses INotifyPropertyChange
, for other things including a name. The ComboBox
populates correctly, but it's initial value isn't being set.
My question is, how can I set the SelectedValue
of the ComboBox
to the appropriate property of the employee?
EDIT: This is my observable collection (a snippet).
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},
};
This is my static resource:
<ObjectDataProvider x:Key="Depts" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="en:department+Department"></x:Type>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
I have actually noticed that whenever I attempt to set SelectedValue or SelectedItem, the combobox turns red (I have a DataGridComboBoxColumn
that is also tied to this, but has an ItemsSource
). Also, I have a ListBox
that also shows the department - however, this one displays the correctly, but doesn't update even when I change the ComboBox
selection for any employee.
Upvotes: 2
Views: 4400
Reputation: 48568
Instead of setting SelectedValue
set SelectedItem
.
To set SelectedValue
you need to have set DisplayMemberPath
and ValueMemberPath
. In your case since its an Enum you can't set them.
So set SelectedItem
like this
<ComboBox x:Name="Form1Combobox"
Width="150"
IsSynchronizedWithCurrentItem="True"
SelectedItem="{Binding Dept}"
ItemsSource="{Binding Source={StaticResource ResourceKey=Depts}}"/>
Upvotes: 3