[英]How to Binding the array[] to the DataGridTextColumn dynamiclly wpf
[英]How to Binding Combobox in DataGridTextColumn in Datatgrid WPF Programmatically
我想要的是我的組合框加載在我的 DataGrid 的第一行中,我的標題由復選框組成
ObservableCollection<dynamic> items = new ObservableCollection<dynamic>();
private IEnumerable<string> PropertyNames; //Store the properties names of the dynamic object
//首先我正在通過Excel讀取我的dt;
DataSet result = new DataSet();
DataTable dt = new DataTable();
if (fileName.EndsWith(".xlsx"))
{
// Reading from a binary Excel file (format; *.xlsx)
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
result = excelReader.AsDataSet();
dt = result.Tables[0];
excelReader.Close();
}
if (fileName.EndsWith(".xls"))
{
// Reading from a binary Excel file ('97-2003 format; *.xls)
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
result = excelReader.AsDataSet();
excelReader.Close();
}
// 然后我根據我的 dt 列數創建我的標題,如附件中所示
for (int i = 0; i < dt.Columns.Count; i++)
{
DataGridTextColumn checkBoxColumn = new DataGridTextColumn();
System.Windows.Controls.CheckBox headerCheckBox = new System.Windows.Controls.CheckBox();
headerCheckBox.Content = "UnNamedColumn" + i;
checkBoxColumn.Header = headerCheckBox;
checkBoxColumn.Binding = new System.Windows.Data.Binding(dt.Rows[0][i].ToString());
dataGrid.Columns.Add(checkBoxColumn);
}
// 我正在嘗試在 DataGrid 的第一行加載組合框
PropertyNames = new List<string>();
items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == 0)
{
dynamic item = new DynamicObjectClass();
for (int j = 0; j < dt.Columns.Count; j++)
{
// DataGridColumn columns = GetNewComboBoxColumn("UnNamedColumn" + j, dt.Rows[0][j].ToString(), binddt)
var cb = new System.Windows.Controls.ComboBox();
cb.ItemsSource = new List<string> { "C50", "C40", "C30" };
cb.SelectedItem = new System.Windows.Data.Binding(dt.Rows[0][j].ToString());
item.TrySetMember(new SetPropertyBinder(dt.Rows[0][j].ToString()), cb);
}
PropertyNames = item.GetDynamicMemberNames();
items.Add(item);
dataGrid.ItemsSource = items;
break;
}
}
// 最后我將整個 dt 附加到數據網格中
for (int i = 0; i < dt.Rows.Count; i++)
{
dynamic item = new DynamicObjectClass();
for (int j = 0; j < dt.Columns.Count; j++)
{
item.TrySetMember(new SetPropertyBinder(dt.Rows[0][j].ToString()), dt.Rows[i][j].ToString());
}
PropertyNames = item.GetDynamicMemberNames();
items.Add(item);
dataGrid.ItemsSource = items;
}
您可以執行以下操作並用您的數據替換List
:
var bindingSource = new BindingSource();
bindingSource.DataSource = new List<string> { "C50", "C40", "C30" };
comboBox1.DataSource = bindingSource.DataSource;
comboBox1.DisplayMember = new System.Windows.Data.Binding(dt.Rows[0][j].ToString());
comboBox1.ValueMember = new System.Windows.Data.Binding(dt.Rows[0][j].ToString());
來源: 如何將列表綁定到組合框?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.