views:

395

answers:

2

I have a datagrid that I want to add a button/s to at runtime. I have managed to do this with the below code:

DataGridTemplateColumn templateCol = new DataGridTemplateColumn();
templateCol.CellTemplate = (System.Windows.DataTemplate)XamlReader.Load(
    @"<DataTemplate xmlns='http://schemas.microsoft.com/client/2007'
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'&gt;
    <Button Content='" + item.Value.Label + @"'/> 
    </DataTemplate>");

_dataGrid.Columns.Add(templateCol);

The problem is that I can't work out how to add a click event. I want to add a click event with a parameter corresponding to the row id...

A: 

That seems a kinda funky way to do it. I would instantiate a new button, set it's attributes (including grid.setcolumn) and add it to the datagrid.children. You could create a loop if you needed a button in every cell.

Handleman
yea, if there was a "non-funky" way of doing it I certainly would like to do it that way! There is no datagrid.children namespace, however... could you supply some code? (I have read that to add a button dynamically you have to do what I have done above; although things could have changed with SL3)
Grayson Mitchell
A: 

OK, you have to attach the event when you load each row! So attach the following to your LoadingRow event...

private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGridRow row = e.Row;
            foreach (DataGridColumn col in _dataGrid.Columns)
            {
                FrameworkElement cellContent = col.GetCellContent(e.Row);
                Button b = cellContent as Button;
                if (b != null)
                {
                    //clear previous event
                    b.Click -= ActionButton_Click;

                    b.Click += new RoutedEventHandler(ActionButton_Click);
                }
            }
        }
Grayson Mitchell

related questions