WPF MVVM 绑定ComboBox数据
一、属性变更基类 NotificationBase.cs
public class NotificationBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
[DataContract]
public abstract class BaseModel : NotificationBase
{
}
二、ViewModel层
public class PageBuildProductsModel : BaseModel
{
//产品列表
private List<ProductsModel> productslist;
public List<ProductsModel> ProductsList
{
get { return productslist; }
set
{
productslist = value;
NotifyPropertyChanged("ProductsList");
}
}
//选中产品
public ProductsModel CurrentProducts { get; set; }
public PageBuildProductsModel()
{
ProductsList = new List<ProductsModel>();
foreach (.....)
{
ProductsList.Add(......);
}
this.CurrentProducts = this.ProductsList[0];
}
private void Build(object obj)
{
//获取选中的值
MessageBox.Show(CurrentProducts.Queries);
}
}
三、View
<ComboBox ItemsSource="{Binding ProductsList}"
Width="100"
DisplayMemberPath="Name"
SelectedItem="{Binding CurrentProducts, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
注意:当前选项,绑定CurrentProducts