2011-05-05 93 views
0

我有以下的組合框是得到populat由枚舉型:WPF組合框的SelectedItem綁定不工作

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

請注意,DataContext獲取的設置代碼隱藏。

它甚至不是雙向綁定,我有一些Product.Status的默認值,但它永遠不會被選中。

更新

有人問我,把我的狀態屬性的代碼。

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 }; 
+0

調試器下運行時,有一個在你的輸出窗口,看看它告訴你關於綁定狀態的東西MVVM光代碼段。 – 2011-05-05 11:05:18

+0

@Russell它什麼都不告訴 – 2011-05-05 11:08:51

+0

你可以給你的狀態屬性的代碼?如果它只是無法綁定,我會在Output窗口中預期一些東西。 – 2011-05-05 11:19:51

回答

1

您的狀態屬性必須通知其更改,並且您的產品類必須實現INotifyPropertyChanged接口。

在這裏,你必須具有該屬性;-)

/// <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); 
      } 
     } 
2

ComboBox綁定有點棘手。確保在分配DataContext時加載itemssource,並且使用SelectedItem分配的項目與ItemsSource中的一個項目符合==關係。

+0

感謝您的回答。 ItemSource被加載,它只是一個靜態枚舉。 – 2011-05-05 10:54:59

+1

你能否提供一些代碼片段? – LueTm 2011-05-05 11:28:14

+0

對於非枚舉類型,在模型類上實現.Equals(對象)是個訣竅。 – 2015-12-16 11:29:48

相關問題