Search code examples
wpfxamlcomboboxselecteditemselectedvalue

Selected item on WPF combobox


I have some wpf combobox (xaml):

<ComboBox ItemsSource="{Binding Path=NonPositionedConcentrators}"
          SelectedValue="{Binding Path=SelectedNonPositionedConcentrator}"
          DisplayMemberPath="SerialNumber" />

SelectedNonPositionedConcentrator - is a Concentrator type. Something like:

class Concentrator
{
...
public string SerialNumber {...}
...
public override ToString{ return "Some needed text..."; }
}

NonPositionedConcentrators - the list of Concentrator objects.

So, in application I see the combobox with serial numbers of NonPositionedConcentrators (because of DisplayMemberPath="SerialNumber"), but when I select something, then selected item shonw as "Some needed text..." , see the image:

enter image description here

I have tried SelectedValuePath="SerialNumber", but it doesn't work... And I can't remove this - public override ToString{ return "Some needed text..."; }, becase I need...


Solution

  • It looks like you have a custom ComboBox template which may be causing your problem. If it is using a TextBlock or ContentPresenter for the display of the selected item which is just binding the SelectedItem property and not pulling in any templates or other settings you would just get the ToString value no matter what. A properly constructed template will have something like what the default template uses at this spot:

    <ContentPresenter ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
        Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}"
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="false" Margin="{TemplateBinding Padding}"
        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>