I have a WPF program that produces several DataGrids. I have added capability to export each grid to Excel using the ideas at this site:
http://www.codeproject.com/Articles/120480/Export-to-Excel-Functionality-in-WPF-DataGrid
Currently I just have a button under each grid that has its own handler that looks something like this:
private void m_btnExportTimePartitionToExcel_Click(object sender, RoutedEventArgs e)
{
try
{
ExportToExcel<SystemTimeRecordData, List<SystemTimeRecordData>> s = new ExportToExcel<SystemTimeRecordData, List<SystemTimeRecordData>>();
ICollectionView view = CollectionViewSource.GetDefaultView(m_gridPartitionSystemTimeRecords.ItemsSource);
s.dataToPrint = (List<SystemTimeRecordData>)view.SourceCollection;
s.GenerateReport();
}
catch (Exception ex)
{
MessageBox.Show("Problem with exporting Excel. Error: " + ex.Message);
}
}
I have a similar button handler for each grid. This all works, but it “smells”. It seems there should be a way to have just one handler that each button calls. That is, if I can pass the grid associated with that button, and the relevant class. Can I do that from XAML? I have searched and seen examples of passing arguments, but not the grid itself and certainly not the class, which I’m guessing would have to be passed as a Type?
It would be nice to replace the above code with something like…
private void m_btnExportTimePartitionToExcel_Click(object sender, RoutedEventArgs e)
{
try
{
// some how get Type type, and grid from sender and/or e
ExportToExcel<type, List<type>> s = new ExportToExcel<type, List<type>>();
ICollectionView view = CollectionViewSource.GetDefaultView(m_grid.ItemsSource);
s.dataToPrint = (List<type>)view.SourceCollection;
s.GenerateReport();
}
catch (Exception ex)
{
MessageBox.Show("Problem with exporting Excel. Error: " + ex.Message);
}
}
Then I could just have one button handler! Any ideas?
Thanks,
Dave
Here are a few ways you could do that:
You could try passing the
DataGridas theCommandParameterif you can find it using anElementNameorRelativeSourcebindingYou could then get the value with
((Button)sender).CommandParameter as DataGridYou could pass the
ItemsSourceas aCommandParameterinstead of the entire DataGridYou could navigate the VisualTree to find the closest DataGrid. I have some helpers on my blog that make this easy. Here’s an example using them with the above XAML:
I’m sure there’s other ways too, but those are the first ones I thought of 🙂