views:

392

answers:

1

Hello guys

I got this cbxJobPosition_SelectionChanged firing as expected. The problem is when a external method tries to set cbxJobPosition.

cbxJobPosition is databinded with a list of objects of type JobPosition:

  • JobPositionID: 1, JobPositionName: Manager

  • JobPositionID: 2, JobPositionName: Employee

  • JobPositionID: 3, JobPositionName: Third party

Here's the XAML:

<ComboBox Cursor="Hand" DataContext="{Binding}" ItemsSource="{Binding}"
FontSize="13" Name="cbxJobPosition"     
SelectedValuePath="JobPositionID" DisplayMemberPath="JobPositionName" 
SelectedIndex="0" Width="233" Height="23" 
SelectionChanged="cbxJobPosition_SelectionChanged" />

On UserControl_Loaded method, it reads from database the list of jobs and try to set the specific job position "Third party":

//calls cbxJobPosition_SelectionChanged and passes the correct SelectedValue within
cbxJobPosition.SelectedIndex = 3;

//calls cbxJobPosition_SelectionChanged and but won't pass the correct SelectedValue within
cbxJobPosition.SelectedValue = "3";

As you can notice, when the processing is automatically redirected to cbxJobPosition_SelectionChanged, the SelectedValue attribute will have different values for each statement above when you're debugging within cbxJobPosition_SelectionChanged event.

Does anyone know if this difference is expected, am I missing something or it could be a bug?

A: 

Is JobPositionID a string? If not, that could explain why it doesn't work. At the databinding level, WPF won't automatically convert string to int. I'm guessing it changes the selection on the box to none when you attempt it.

RandomEngy
JobPositionID is int
Junior Mayhé
I came up with searching the element with LINQ and setting combobox's SelectedItem with the found object and executing SelectionChanged statements (on an external method). I may say that I don't like this solution.
Junior Mayhé
Well I don't know all the details of what you're doing, but at least for the example, you could parse "3" into an int, then use it to set SelectedValue.
RandomEngy
Yes. I pass an int like 3 to cbxJobPosition.SelectedValue = 3; when redirected to cbxJobPosition_SelectionChanged, cbxJobPosition.SelectedValue is null! Quite wierd!
Junior Mayhé
(e.Source as ComboBox) and (e.OriginalSource as ComboBox).SelectedValue are also null
Junior Mayhé
Oh, my bad. Passing in "3" as a string should work just fine. Looks like you're running into this bug: http://stackoverflow.com/questions/247413/wpf-combobox-selectedvalue-not-updating-from-binding-source . In short, SelectedValue only works well for get operations, not set.
RandomEngy