Chris Roeder Chris Roeder - 1 year ago 159
C# Question

WPF- Combobox Binding

I have a class named "employee":

public string Forname { get; set; }
public string Lastname { get; set; }
public EmployeeGroup Group { get; set; }


a class "EmployeeGroup":

public string Groupname { get; set; }
public short GroupID { get; set; }


and a wpf:

<ComboBox x:Name="cmbGroup" SelectedItem="{Binding Group}" HorizontalAlignment="Left" Margin="342,226,0,0" VerticalAlignment="Top" Width="129"/>
<TextBox x:Name="txtForename" Text="{Binding Forname}" HorizontalAlignment="Left" Height="24" Margin="342,21,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="129" VerticalContentAlignment="Center" GotFocus="SelectText"/>
<TextBox x:Name="txtLastname" Text="{Binding Lastname}" HorizontalAlignment="Left" Height="24" Margin="342,47,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="129" VerticalContentAlignment="Center" GotFocus="SelectText"/>
<ListBox x:Name="lstEmployee" HorizontalAlignment="Left" Height="362" Margin="25,19,0,0" VerticalAlignment="Top" Width="217" SelectionChanged="lstEmployee_SelectionChanged"/>


The ComboBox and the ListBox gets the source from the code-behind-file (a ObservableCollection):

cmbGroup.ItemsSource = Database_Contract.GetListOfContract();
lstEmployee.ItemsSource = Database_Employee.GetListOfEmployee();


And I set the DataContext when an employee is selected in the ListBox in the code-behind-file of the wpf:

DataContext = lstEmployee.SelectedItem;


The binding with the ListBox and TextBoxes works fine, but I have a problem with the Combobox:
The source works, means that i can select different Groups. But there is no binding to the selected employee. So when I select the employee, the TextBoxes with the fore- and lastname filled right, but the Combobox ist emtpy. But when I click the Combobox, then I can choose from the given Groups.

So what I've done wrong?

Edit:
When I set the Binding of the ComboBox.SelectedIndex to the Group.GroupID, then it works. But it's not guaranteed that the GroupID and the ComboBox-Index is the same.

Answer Source

I found a solution... I've changed to MVVM, set the binding of the cmbGroup to the ListOfGroup, overridden the GetHashCode and Equals methods of the class EmployeeGroup, and it works. Thanks guys!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download