How to define a Click Button handler in a XAML programmatic definition

I am dynamically creating columns for a data grid in a user control in Silverlight 4 that is working correctly. The first column of the data grid is the button, so I use the following code to add a 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 exit the Click = "performFastSearch" command, but breaks with a "crossappdomainmarshaledexception" when I add it.

Is this how I should try to add a click handler method, or should I use something else?

+3
source share
1 answer

XAML, , Click, , XAML , , Visual Studio, , XAML , .

, , Button, . :

    void grid_LoadingRow(object sender, DataGridRowEventArgs e) 
    { 
        var btnCol =  
        m_DataGrid.Columns.FirstOrDefault(
                c => c.GetValue(FrameworkElement.NameProperty) as string == "m_BtnColumn");

        FrameworkElement el = btnCol.GetCellContent(e.Row);

        Button btn = el as Button;

        if (btn != null) 
        {    
            btn.Click -= new RoutedEventHandler(btn_Click); 
            btn.Click += new RoutedEventHandler(btn_Click); 
        } 
    }


    void btn_Click(object sender, RoutedEventArgs e) 
    { 

    }
+4

All Articles