您可能指的是2个问题。第一个是设置 dgcbc.ItemsSource = columnList 不足以使 ComboBox 显示可供选择的项目列表。
根据 columnList 的类型,您需要设置 DisplayMemberPath 和 SelectedValuePath 属性,例如:
var columnList = new Dictionary<string, string>
{
{ "123", "test 123" },
{ "aaa", "test aaa" },
{ "qwe", "test qwe" }
};
dgcbc.ItemsSource = columnList;
dgcbc.DisplayMemberPath = "Key";
dgcbc.SelectedValuePath = "Value";
另一个问题是将列绑定到在 DataGrid 对象上设置的 ItemsSource。
dg2.ItemsSource = dt;
dgcbc.TextBinding = new Binding(string.Format("[{0}]", "Column_Name");
您可能还想知道如何在 DataGridTextColumn 中显示文本:
dgtc.Binding = new Binding(string.Format("[{0}]", "Column_Name");
我不确定这是否是您想要实现的列映射,可能您想修改网格的标题模板并将网格数据显示为下面的文本。为此,请使用DataGridTemplateColumn DataGridTextColumn 列,其标题中包含标题标签和组合框。希望能帮助到你。
编辑:
我准备了一个快速而肮脏的代码解决方案。
XAML:
<DataGrid x:Name="dg" Grid.Row="0" AutoGenerateColumns="False"/>
后面的代码:
// data is a rough equivalent of DataTable being imported
var data = new List<Dictionary<string, string>>
{
new Dictionary<string, string> { { "column1", "asd asfs af" }, { "column2", "45dfdsf d6" }, { "column3", "7hgj gh89" } },
new Dictionary<string, string> { { "column1", "aaasdfda" }, { "column2", "45sdfdsf 6" }, { "column3", "78gh jghj9" } },
new Dictionary<string, string> { { "column1", "s dfds fds f" }, { "column2", "4dsf dsf 56" }, { "column3", "78gh jgh j9" } },
};
// a list of columns to map to
var importToColumns = new List<string>
{
"123",
"aaa",
"qwe",
"456",
"bbb"
};
importMappings = new Dictionary<string, int>();
foreach(var column in data[0])
{
importMappings.Add(column.Key, -1);
}
foreach(var r in importMappings)
{
var dgtc = new DataGridTextColumn();
dgtc.Binding = new Binding(string.Format("[{0}]", r.Key));
var sp = new StackPanel();
dgtc.Header = sp;
sp.Children.Add(new Label { Content = r.Key });
var combo = new ComboBox();
sp.Children.Add(combo);
combo.ItemsSource = importToColumns;
var selectedBinding = new Binding(string.Format("[{0}]", r.Key));
selectedBinding.Source = importMappings;
combo.SetBinding(Selector.SelectedIndexProperty, selectedBinding);
dgtc.MinWidth = 100;
dgtc.CanUserSort = false;
dg.Columns.Add(dgtc);
}
dg.ItemsSource = data;
}
private Dictionary<string, int> importMappings;
选择被批准后,importMappings 将包含列映射列表 - 对于每个导入文件列,它将包含 importToColumns 列表中的元素索引,如果没有选择任何元素,则为 -1。