Reputation: 125
I have short xaml code :
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Category}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Category}" KeyUp="TextBox_KeyUp"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
But I dont know how to convert it on c#. I did that: but it dont work, and dont know how add Event to TextBox:
Edit: dont throw exception, but still dont work. Without event.
var a = new DataGridTemplateColumn() { Header = "Kategoria", Width = new DataGridLength(1, DataGridLengthUnitType.Star) };
var aa = new DataTemplate();
aa.Resources.Add(1, new TextBlock() { Text = new Binding("Category").ToString() });
a.CellTemplate = aa;
var aaa = new DataTemplate();
aaa.Resources.Add(2, new System.Windows.Controls.TextBox() { Text = new Binding("Category").ToString() });
a.CellEditingTemplate = aaa;
ProjectDataGrid.Columns.Add(a);
ProjectDataGrid.Columns.Add(new DataGridTextColumn() { Header = "Mnemonik", Binding = new Binding("Mnemoniese"), Width = new DataGridLength(1, DataGridLengthUnitType.Star) });
Upvotes: 1
Views: 59
Reputation: 76
I think it might be helpful. I just convert your XAML markup in C# code step by step.
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn
{
CellTemplate = new DataTemplate
{
DataType = typeof(TextBlock)
},
CellEditingTemplate = new DataTemplate
{
DataType = typeof(TextBox)
}
};
FrameworkElementFactory CategoryBlock = new FrameworkElementFactory(typeof(TextBlock));
CategoryBlock.SetBinding(TextBlock.TextProperty, new Binding("Category"));
templateColumn.CellTemplate.VisualTree = CategoryBlock;
FrameworkElementFactory CategoryTextBox = new FrameworkElementFactory(typeof(TextBox));
CategoryTextBox.SetBinding(TextBox.TextProperty, new Binding("Category"));
CategoryTextBox.AddHandler(KeyUpEvent, new KeyEventHandler(TextBox_KeyUp));
templateColumn.CellEditingTemplate.VisualTree = CategoryTextBox;
ProjectDataGrid.Columns.Add(templateColumn);
Upvotes: 2