[英]WPF ComboBox SelectedItem Binding Doesn't Work
I have the following ComboBox that gets populat from an enum:我有以下 ComboBox 从枚举中获取:
<ComboBox Name="cmbProductStatus" ItemsSource="{Binding Source={StaticResource statuses}}"
SelectedItem="{Binding Path=Status}" />
Please, note that the DataContext gets set in code-behind.请注意,DataContext 是在代码隐藏中设置的。
It's not even about two-way binding, I have some default value for Product.Status but it never gets selected.它甚至不是双向绑定,我有一些 Product.Status 的默认值,但它永远不会被选中。
Updated更新
I was asked to put code of my Status property.我被要求输入我的 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 binding is a little tricky. ComboBox 绑定有点棘手。 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.
确保在分配 DataContext 时加载了 itemssource,并且使用 SelectedItem 分配的项目满足与 ItemsSource 中的一项的 == 关系。
Your status property must notify its change and your Product class must implement INotifyPropertyChanged
interface.您的状态属性必须通知其更改,并且您的产品 class 必须实现
INotifyPropertyChanged
接口。
Here you have the MVVM Light code snippet for the property;-)在这里,您有该属性的 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.