1

Not sure why I cant get this to work. I have a combobox in WPF. Want to loop through all the controls and set active where criteria are met. I find the match, but cant seem to set the value. this example is modeled after the "selected value" approach... Set SelectedItem of WPF ComboBox

 bool match = false;
            foreach (ComboBoxItem cbi in cb_Divisinos.Items)
            {
                if (cbi.Content.ToString().Split('-')[0].Trim() == family.Division.ToString()) {
                    cb_Divisinos.SelectedValue = cbi.Content.ToString();
                    match = true;
                }
            }
Skinner
  • 1,461
  • 4
  • 17
  • 27

3 Answers3

0

If I could see your XAML, it'd be helpful, but if I had to guess I would say that most likely you aren't setting the SelectedValuePath on the ComboBox element in XAML.

<ComboBox Grid.Row="1" Grid.Column="0" 
          Name="combo" SelectedValuePath="Content">

In order for this process to work correctly though, the items should also be defined in the XAML and not through a bound items source. If you are binding to an Items Source, then you would need to use the SelectedItem approach instead.

If I could currently do this as a comment, I would, but alas I've created a newer profile and I cannot.

0

If your ComboBox is explicitly populated with ComboBoxItems like this:

<ComboBox x:Name="cb_Divisinos">
    <ComboBoxItem>Division A - xyz</ComboBoxItem>
    <ComboBoxItem>Division B - abc</ComboBoxItem>
</ComboBox>

...you can simply set the SelectedItem property to the ComboBoxItem that you want to select:

bool match = false;
foreach (ComboBoxItem cbi in cb_Divisinos.Items)
{
    if (cbi.Content.ToString().Split('-')[0].Trim() == family.Division.ToString())
    {
        cb_Divisinos.SelectedItem = cbi;
        match = true;
        break;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

Another approach, which works better for me, is to select the item using SelectedIndex as following:

bool match = false;
int selectedIndexNumber = 0;
            foreach (ComboBoxItem cbi in cb_Divisinos.Items)
            {
                if (cbi.Content.ToString().Split('-')[0].Trim() == family.Division.ToString()) {
                    cb_Divisinos.SelectedValue = cbi.Content.ToString();
                    match = true;
                    break;
                }
                    selectedIndexNumber += 1;

            }

then apply the selectedindex like...

cb_Divisinos.SelectedIndex = selectedIndexNumber;

in the ComboBox set the Binding for SelectedIndex...

<ComboBox Name="cb_Divisinos" ItemsSource="{Binding }"
          DisplayMemberPath="Name"
          SelectedValuePath="CategoryID" SelectedIndex="{Binding Mode=OneWay}">
</ComboBox>

You don't need to specify a value or fieldname for SelectedIndex Binding; just set it as i have shown above.

sheraz yousaf
  • 79
  • 3
  • 7