Я хотел бы отобразить DataGrid, который будет содержать данные, загруженные из источника данных в DataTable. Столбцы будут отличаться каждый раз, и некоторые из них должны быть представлены с помощью ComboBox.
Как мне настроить DataGridTemplateColumn для столбца, для которого требуется ComboBox, во время выполнения?
Хорошо, это самое близкое, что у меня есть с помощью @Meleak, почти там, просто отображение ключа, а не значения, когда сетка не редактируется.
открытый частичный класс MainWindow: Window
{
общедоступный словарь MyDictionary {get; задавать; }
public MainWindow()
{
InitializeComponent();
//Init Dictionary
this.MyDictionary = new Dictionary<int, string>();
this.MyDictionary.Add(1, "Value 1");
this.MyDictionary.Add(2, "Value 2");
this.MyDictionary.Add(3, "Value 3");
DataTable dt = new DataTable();
DataColumn column = new DataColumn("MyTypeId", typeof(int));
dt.Columns.Add(column);
DataRow newRow = dt.NewRow();
newRow["MyTypeId"] = 1;
dt.Rows.Add(newRow);
dataGrid.Columns.Add(GetNewComboBoxColumn("My Type", "MyTypeId", this.MyDictionary));
this.DataContext = dt;
}
public static DataGridTemplateColumn GetNewComboBoxColumn(string header,
string bindingPath,
object itemsSource)
{
DataGridTemplateColumn comboBoxColumn = new DataGridTemplateColumn();
comboBoxColumn.Header = header;
Binding textBinding = new Binding();
textBinding.Path = new PropertyPath(bindingPath);
FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.MarginProperty, new Thickness(3, 3, 3, 3));
textBlock.SetBinding(TextBlock.TextProperty, textBinding);
FrameworkElementFactory comboBox = new FrameworkElementFactory(typeof(ComboBox));
comboBox.SetValue(ComboBox.MarginProperty, new Thickness(1, 1, 1, 1));
comboBox.SetBinding(ComboBox.TextProperty, textBinding);
comboBox.SetValue(ComboBox.SelectedValuePathProperty, "Key");
comboBox.SetValue(ComboBox.DisplayMemberPathProperty, "Value");
Binding itemsSourceBinding = new Binding();
itemsSourceBinding.Source = itemsSource;
comboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSourceBinding);
comboBoxColumn.CellTemplate = new DataTemplate();
comboBoxColumn.CellTemplate.VisualTree = textBlock;
comboBoxColumn.CellEditingTemplate = new DataTemplate();
comboBoxColumn.CellEditingTemplate.VisualTree = comboBox;
return comboBoxColumn;
}
}