简体   繁体   中英

Can't bind value to combobox in wpf

I have a control,where is combox. I bind to it properties from modelview. I can bind properties to textboxes, but not to combobox. Value from modelview is 4. Anyone know why is that ?

<ComboBox  HorizontalAlignment="Left" VerticalAlignment="Top" SelectedItem="{Binding Path=QuantityOfStars}">

                                    <ComboBoxItem Content="0"></ComboBoxItem>

                                    <ComboBoxItem Content="1"></ComboBoxItem>

                                    <ComboBoxItem Content="2"></ComboBoxItem>

                                    <ComboBoxItem Content="3"></ComboBoxItem>

                                    <ComboBoxItem Content="4"></ComboBoxItem>

                                    <ComboBoxItem Content="5"></ComboBoxItem>

                               </ComboBox>


public int QuantityOfStars
        {
            get
            {
                return this.ReporterHotelDescription.QuantityOfStars;

            }
            set
            {
                this.ReporterHotelDescription.QuantityOfStars = value;
                NotifyChanged("QuantityOfStars");
            }
        }

You filled your ComboBox with ComboBoxItems, not integers, so it cannot convert them to an integer to bind to your property. Either fill the ComboBox with integers manually:

<ComboBox 
    HorizontalAlignment="Left" VerticalAlignment="Top" SelectedItem="{Binding Path=QuantityOfStars}"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:Int32>0</sys:Int32>
    <sys:Int32>1</sys:Int32>
    <sys:Int32>2</sys:Int32>
    <sys:Int32>3</sys:Int32>
    <sys:Int32>4</sys:Int32>
    <sys:Int32>5</sys:Int32>
</ComboBox>

Or, bind the ItemsSource property on the ComboBox to a property in your ViewModel that is a list of the appropriate integers.

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