欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF MVVM 绑定ComboBox数据

程序员文章站 2022-06-07 18:42:37
...

一、属性变更基类 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