WPF组合框选中的项目绑定不起作用
本文关键字:项目 绑定 不起作用 组合 WPF | 更新日期: 2023-09-27 17:54:45
我有以下ComboBox,从enum流行:
<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 };
ComboBox绑定有点棘手。确保itemssource在您分配DataContext时被加载,并且您用SelectedItem分配的项目满足itemssource中一个项目的==关系。
你的status属性必须通知它的变化,并且你的Product类必须实现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);
}
}