开发者

WPF ComboBox SelectedItem Binding Doesn't Work

开发者 https://www.devze.com 2023-03-02 19:58 出处:网络
I have the following ComboBox that gets populat from an enum: <ComboBox Name=\"cmbProductStatus\" ItemsSource=\"{Binding Source={StaticResource statuses}}\"

I have the following ComboBox that gets populat from an enum:

<ComboBox Name="cmbProductStatus" ItemsSource="{Binding Source={StaticResource statuses}}" 
                                                  SelectedItem="{Binding Path=Status}" />

Please, note that the DataContext gets set in code-behind.

It's not even about two-way binding, I have some default value for Product.Status but it never gets selected.

Updated

I was asked to put code 开发者_如何学运维of my Status property.

public class Product    {
    //some other propertties
    private ProductStatus _status = ProductStatus.NotYetShipped;
    public ProductStatus Status { get { return _status; } set { value = _status; } }
}

public enum ProductStatus { NotYetShipped, Shipped };


ComboBox binding is a little tricky. Make sure that the itemssource is loaded when you assign the DataContext and that the item you assign with SelectedItem meets the == relation with one item in the ItemsSource.


Your status property must notify its change and your Product class must implement INotifyPropertyChanged interface.

Here you have the MVVM Light code snippet for the property ;-)

/// <summary>
        /// The <see cref="MyProperty" /> property's name.
        /// </summary>
        public const string MyPropertyPropertyName = "MyProperty";

        private bool _myProperty = false;

        /// <summary>
        /// Gets the MyProperty property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool MyProperty
        {
            get
            {
                return _myProperty;
            }

            set
            {
                if (_myProperty == value)
                {
                    return;
                }

                var oldValue = _myProperty;
                _myProperty = value;

                // Remove one of the two calls below
                throw new NotImplementedException();

                // Update bindings, no broadcast
                RaisePropertyChanged(MyPropertyPropertyName);

                // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
                RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消