简体   繁体   中英

WPF combobox binding and SelectedItem

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?

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

See this answer Difference between SelectedItem, SelectedValue and SelectedValuePath

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM