簡體   English   中英

從WPF中按XAML按鈕發送網格名稱和類名稱

[英]Sending Grid name and class name from XAML button press in WPF

我有一個WPF程序,可以產生幾個DataGrid。 我增加了使用此站點上的想法將每個網格導出到Excel的功能: http : //www.codeproject.com/Articles/120480/Export-to-Excel-Functionality-in-WPF-DataGrid

目前,我在每個網格下都有一個按鈕,每個按鈕都有自己的處理程序,看起來像這樣:

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);
        }
    }

對於每個網格,我都有一個類似的按鈕處理程序。 所有這些都有效,但是它“聞起來”。 似乎應該有一種方法可以讓每個按鈕僅調用一個處理程序。 也就是說,如果我可以傳遞與該按鈕關聯的網格以及相關的類。 我可以通過XAML做到嗎? 我搜索並看到了傳遞參數的示例,但沒有網格本身,當然也沒有類,我猜想必須將其作為類型傳遞? 最好將上面的代碼替換為...

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);
        }
    }

然后,我只需要一個按鈕處理程序即可! 有任何想法嗎? 謝謝戴夫

您可以通過以下幾種方法做到這一點:

  • 如果可以使用ElementNameRelativeSource綁定找到DataGrid ,則可以嘗試將DataGrid作為CommandParameter傳遞

     <Button CommandParameter="{Binding ElementName=DataGridA}" ... /> <!-- Will only work if this is inside the DataGrid somewhere, like in the footer --> <Button CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}" ... /> 

    然后可以使用((Button)sender).CommandParameter as DataGrid獲取值

  • 您可以將ItemsSource作為CommandParameter而不是整個DataGrid傳遞

     <StackPanel> <DataGrid ItemsSource="{Binding SomeCollection}" ... /> <Button CommandParameter="{Binding SomeCollection}" ... /> </StackPanel> 
  • 您可以瀏覽VisualTree以找到最接近的DataGrid。 我的博客上有一些幫助程序,可簡化此過程。 這是將它們與上述XAML結合使用的示例:

     var parentPanel = VisualTreeHelpers.FindAncestor<StackPanel>((Button)sender); var datagrid = VisualTreeHelpers.FindChild<DataGrid>(parentPanel); 

我敢肯定還有其他方法,但是那是我想到的第一個方法:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM