How to register Button ClickHandler of button in DataGrid in TemplateControl

Damir Dobric Posts

Next talks:



Follow me on Twitter: #ddobric




Registering of Click event of a button contained in the datatemplate of datagrid which is contained in Silverlight TemplateControl can be triky.
For this reason I pasted here a peace of XAML which contains that grid and corresponding code which subscribes Click-events.

  <data:DataGridTemplateColumn Header=""  x:Name="m_BtnColumn">

<Button x:Name="m_Button" Tag="{Binding .}" >



To make all this working in ApplyTemplate of you remplate controll following has to be done


m_DataGrid = GetTemplateChild("m_DataGrid") as DataGrid;

if (m_DataGrid == null)
throw new Exception("");

DataGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(grid_LoadingRow);


Then implement the code which subscribes events:


    void grid_LoadingRow(object sender, DataGridRowEventArgs e)
            var btnCol = 

                    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)




Another interesting DataGrid example related to this post can be found here.

Posted Feb 03 2011, 11:07 AM by Damir Dobric
Filed under: is a .Net Community Blog powered by daenet GmbH.