0

I have a list containing instances of the following class:

namespace Foo.InformationModel.Reference
{
    public class ReferenceCodeTypeChar
    {
        public ReferenceCodeTypeChar();

        public string Category { get; set; }
        public string CodeValue { get; set; }
        public string Description { get; set; }
        public string Value { get; set; }
    }
}

Here is the object that is used as the DataContext for the window in which the combobox is and its related properties:

public class MyObject
{
    public List<Foo.InformationModel.Reference.ReferenceCodeTypeChar> ProgramTypes() {...}

    private string _selectedProgramTypeCode;
    public string SelectedProgramTypeCode
    {
        get
        {
            return _selectedProgramTypeCode;
        }
        set
        {
            if (_selectedProgramTypeCode != value)
            {
                _selectedProgramTypeCode = value;
                OnPropertyChanged("SelectedProgramTypeCode");
            }
        }
    }
}

Here is the xaml code behind for the combobox:

<ComboBox ItemsSource="{Binding Path=ProgramTypes}"
          SelectedItem="{Binding Path=SelectedProgramTypeCode, Mode=TwoWay}"
          DisplayMemberPath="Description"
          SelectedValuePath="Value"/>

The problem happens inside SelectedProgramTypeCode. The value of the "value" variable is Foo.InformationModel.Reference.ReferenceCodeTypeChar instead of the expected string of Value property of the ReferenceCodeTypeChar object. What is wrong?

Yael
  • 1,566
  • 3
  • 18
  • 25
laconicdev
  • 6,360
  • 11
  • 63
  • 89
  • @Hopeless You should write this as an answer, because it is true. – Michael Mairegger Oct 06 '15 at 15:16
  • well I was wrong with a quick glance at the XAML. Looks like the `SelectedItem` is bound wrong. It should be bound to a property of type `Foo.InformationModel.Reference.ReferenceCodeTypeChar`, in this case you bind it to a string property. In the way from `SelectedItem` to `SelectedProgramTypeCode`, there is no Converter, so `ToString()` will be called on `SelectedItem` and resolved to `"Foo.InformationModel.Reference.ReferenceCodeTypeChar"` before being set to `SelectedProgramTypeCode` (so you see it in `value` variable). – Hopeless Oct 06 '15 at 15:31

2 Answers2

3

You have to use SelectedItem or SelectedValuePath in conjunction with SelectedValue.

See this answer Difference between SelectedItem, SelectedValue and SelectedValuePath

Community
  • 1
  • 1
Giangregorio
  • 1,482
  • 2
  • 11
  • 12
0

You should have used SelectedValue instead of SelectedItem in your XAML.

<ComboBox 
  ItemsSource="{Binding Path=ProgramTypes}"
  SelectedValue="{Binding Path=SelectedProgramTypeCode, Mode=TwoWay}"
  DisplayMemberPath="Description"
  SelectedValuePath="Value" />
filhit
  • 2,084
  • 1
  • 21
  • 34