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

wpf ComboBox 绑定数据

程序员文章站 2022-03-04 11:27:50
...

ComboBox 绑定 DataTable 数据

DeviceTypeViewModel deviceTypeModel = new DeviceTypeViewModel();
this.parentIdTxt.ItemsSource = deviceTypeModel.GetDeviceType().DefaultView;
this.parentIdTxt.DisplayMemberPath = "name";
this.parentIdTxt.SelectedValuePath = "id";

但我们经常会在诸如分类时添加*分类选项,所以我是这样做的,先把数据加入Dictionary,在使用Dictionary作为数据源

public Dictionary<int, string> ComboboxItem()
        {
            DataTable deviceTypes = GetDeviceType();
            Dictionary<int, string> items = new Dictionary<int, string>();
            items.Add(0, "*分类");
            foreach (DataRow row in deviceTypes.Rows)
            {
                items.Add(Convert.ToInt32(row["id"]), row["name"].ToString());
            }
            return items;
        }
DeviceTypeViewModel deviceTypeModel = new DeviceTypeViewModel();
Dictionary<int, string> items = deviceTypeModel.ComboboxItem();
this.parentIdTxt.ItemsSource = items;
this.parentIdTxt.DisplayMemberPath = "Value";
this.parentIdTxt.SelectedValuePath = "Key";