[英]WPF ComboBox SelectedItem Binding Doesn't Work
我有以下 ComboBox 從枚舉中獲取:
<ComboBox Name="cmbProductStatus" ItemsSource="{Binding Source={StaticResource statuses}}"
SelectedItem="{Binding Path=Status}" />
請注意,DataContext 是在代碼隱藏中設置的。
它甚至不是雙向綁定,我有一些 Product.Status 的默認值,但它永遠不會被選中。
更新
我被要求輸入我的 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 };
ComboBox 綁定有點棘手。 確保在分配 DataContext 時加載了 itemssource,並且使用 SelectedItem 分配的項目滿足與 ItemsSource 中的一項的 == 關系。
您的狀態屬性必須通知其更改,並且您的產品 class 必須實現INotifyPropertyChanged
接口。
在這里,您有該屬性的 MVVM Light 代碼片段;-)
/// <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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.