I am dynamically creating the columns for a data grid in a User control in Silverlight 4 which is working correctly.
The first column of the data grid is a button so I am using the following code to add the DataTemplate for the DataGrid:
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = "Search";
StringBuilder sb = new StringBuilder();
sb.Append("<DataTemplate ");
sb.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
sb.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>");
sb.Append("<Button Name='searchBtn' Width='25' Height='20' Click='performFastSearch' >");
sb.Append("<Image Source='http://localhost/SiteAssets/img/Homepage/ribbon_top_right.png' Stretch='None' />");
sb.Append("</Button>");
sb.Append("</DataTemplate>");
templateColumn.CellTemplate = (DataTemplate)XamlReader.Load(sb.ToString());
The code works if I leave the Click=”performFastSearch” part out but breaks with a ‘crossappdomainmarshaledexception’ when I add it in.
Is this how I should be trying to add the click handler method or should I be using something else?
The XAML syntax you are using, where you specify a named method for the Click event only works if the XAML is defined within a user control, in this context, the code generated by Visual Studio will automatically wire-up your click handler. As you are creating your XAML in code, you will have to locate this Button when it is generated and wire up the click handler yourself.
When each row is rendered, handle the loading event to find the Button then wire-up. This blog post might help you: