I am loading datatemplates to my TabControl dynamicly at runtime. For each tab im displaying the proper datagrid for that type using ContentTemplateSelector="{StaticResource DetailsDataGridTemplateSelector}" I need to register KeyDown on the datagrid within the template. This works if used in xaml of cource. But when trying to parse xaml in run-time it fails for:
KeyDown=""DataGrid_KeyDown""
public DataTemplate CreateTemplate(IEnumerable<string> model)
{
string xamlTemplate = $@"<DataTemplate>
<DataGrid ItemsSource=""{{Binding Items}}"" AutoGenerateColumns=""False""
SelectionMode=""Extended"" SelectionUnit=""Cell"" KeyDown=""DataGrid_KeyDown"">
<DataGrid.Columns> ";
foreach (var prop in model)
{
xamlTemplate += $@"<DataGridTextColumn Header=""{prop}"" Binding=""{{Binding {prop},
UpdateSourceTrigger=PropertyChanged}}""/>";
}
xamlTemplate += @"</DataGrid.Columns>
</DataGrid>
</DataTemplate>";
var context = new ParserContext();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
var template = (DataTemplate)XamlReader.Parse(xamlTemplate, context);
return template;
}
System.Windows.Markup.XamlParseException: ''Failed to create a 'KeyDown' from the text 'DataGrid_KeyDown'.' Line number '2' and line position '127'.' ArgumentException: Cannot bind to the target method because its signature is not compatible with that of the delegate type.
How can I attach a keydown event handler for the control inside the template when parsing at runtime?