Anto
Anto

Reputation: 419

How to define Button click handler in programmatic XAML definition

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?

Upvotes: 3

Views: 1202

Answers (1)

ColinE
ColinE

Reputation: 70122

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:

    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) 
    { 

    }

Upvotes: 4

Related Questions