有兩個問題可能涉及到。 首先是設置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對象(S)上設置的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列,其標題中包含標題Label和ComboBox。 希望它有幫助。
編輯:
我準備了一個快速和骯髒的代碼,唯一的解決辦法。
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。
'columnList'從哪裏來?我猜是'null'或空... – 2014-10-17 12:01:59
SqlConnection conn =新的SqlConnection(「服務器= ***;數據庫= ***;集成安全性= true」); string [] restrictions = new string [4] {null,null,「orders」,null}; conn.Open(); var columnList = conn.GetSchema(「Columns」,restrictions).AsEnumerable()。Select(s => s.Field(「Column_Name」))。ToList(); 這足以確保columnList不爲空,它有4個字符串,我甚至測試過它.. –
2014-10-17 16:55:33