Button in a Column Header

Apr 27, 2009 at 5:11 PM
I have the need to have a button in the header of a single column of my datagrid.  

Is this possible?

Thanks,
Tracy
Apr 28, 2009 at 5:55 AM
<tk:DataGrid>
    <tk:DataGrid.Columns>
        <tk:DataGridTextColumn Binding="{Binding}">
            <tk:DataGridTextColumn.Header>
                <Button Content="Header Button" />
            </tk:DataGridTextColumn.Header>
        </tk:DataGridTextColumn>
    </tk:DataGrid.Columns>
</tk:DataGrid>
Apr 28, 2009 at 2:05 PM
This worked like a charm.

Is is possible to add the onClick event delegate in the code behind instead of in the XAML?  I am concerned on the implicite delegates and possible memory leaks.

Thanks!
Apr 29, 2009 at 6:19 AM
You can set up event handlers in code-behind in the same way regardless of where in the visual tree the control happens to be.
Apr 29, 2009 at 9:38 AM
Could you give me a short sample?  If my columns are defined in the XAML, like shown above, how do I gain access to them easily from the "code behind".  


I've been able to accomplish this for named elements at the outer level (like a named button or a named textbox) but not for inner elements like the columns.


e.g. 
this.myDataGrid.event += eventhandler etc
or 
this.myButton.someevent += ...


Thanks
Apr 29, 2009 at 12:13 PM
You just need to give each element that you want to be able to access easily from code-behind a name. Look at x:Name.
Apr 29, 2009 at 12:37 PM
OK.  

I'll give it a try and post back.

Thanks!


Apr 29, 2009 at 1:30 PM
Perfect!  Here is a snippet for others in the future:

<my:DataGridTextColumn.Header>
                        <StackPanel>
                            <TextBlock>TEXT</TextBlock>
                            <Button Content="Header Button" x:Name="HeaderButton" />
                        </StackPanel>
                </my:DataGridTextColumn.Header>



public GridSampleView()
        {
            InitializeComponent();

            //add button click delegate to the headerbutton
            this.HeaderButton.Click += new RoutedEventHandler(HeaderButton_Click);
        }