WPF datagrid cell vertical center, cell auto adapt to data cell width,alternationcount ItemsControl.AlternationIndex

//datagrid cell verticalalignment center
 <DataGrid.CellStyle>
     <Style TargetType="DataGridCell">
         <Setter Property="VerticalContentAlignment" Value="Center"/>
         <Setter Property="Template">
             <Setter.Value>
                 <ControlTemplate TargetType="DataGridCell">
                     <Grid Background="{TemplateBinding Background}">
                         <ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                     </Grid>
                 </ControlTemplate>
             </Setter.Value>
         </Setter>
     </Style>
 </DataGrid.CellStyle>

 

//alternation count
      AlternationCount="7">
<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Style.Triggers>
            <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                <Setter Property="Background" Value="Red"/>
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                <Setter Property="Background" Value="Orange"/>
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="2">
                <Setter Property="Background" Value="Yellow"/>
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="3">
                <Setter Property="Background" Value="Green"/>                            
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="4">
                <Setter Property="Background" Value="Blue"/>                            
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="5">
                <Setter Property="Background" Value="Cyan"/>
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="6">
                <Setter Property="Background" Value="Purple"/>
            </Trigger>
        </Style.Triggers>
    </Style>               
</DataGrid.RowStyle>

 

image

 

 

 

 

 

image

 

 

 

image

 

 

 

 

 

 

image

 

 

image

 

//xaml
<Window x:Class="WpfApp24.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp24"
        WindowState="Maximized"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="dg"
                  FontSize="30"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  VirtualizingPanel.IsVirtualizing="False"
                  VirtualizingPanel.IsContainerVirtualizable="False"
                  VirtualizingPanel.IsVirtualizingWhenGrouping="False"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  ColumnWidth="Auto"
                  MinRowHeight="50"
                  RowHeight="70"
                  AlternationCount="7">
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Style.Triggers>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                            <Setter Property="Background" Value="Red"/>
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                            <Setter Property="Background" Value="Orange"/>
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="2">
                            <Setter Property="Background" Value="Yellow"/>
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="3">
                            <Setter Property="Background" Value="Green"/>                            
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="4">
                            <Setter Property="Background" Value="Blue"/>                            
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="5">
                            <Setter Property="Background" Value="Cyan"/>
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="6">
                            <Setter Property="Background" Value="Purple"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>               
            </DataGrid.RowStyle>
            <DataGrid.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="VerticalContentAlignment" Value="Center"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="DataGridCell">
                                <Grid Background="{TemplateBinding Background}">
                                    <ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                </Grid>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGrid.CellStyle>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export As PDF"
                              Command="{Binding ExportAsPDFCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource 
                        Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>
    </Grid>
</Window>


//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.Packaging;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;

namespace WpfApp24
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            dg.AutoGeneratingColumn+=Dg_AutoGeneratingColumn;
            var vm = new MainVM();
            this.DataContext=vm;
        }

        private void Dg_AutoGeneratingColumn(object? sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);
        }
    }


    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
            InitData();
        }

        private void InitData()
        {
            BooksCollection=new ObservableCollection<Book>();
            for(int i=0;i<100;i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id=i+1,
                    Name=$"Name_{i+1}",
                    Title=$"Title_{i+1}",
                    ISBN1=$"ISBN1_{Guid.NewGuid().ToString("N")}",
                    ISBN2=$"ISBN2_{Guid.NewGuid().ToString("N")}",
                    ISBN3=$"ISBN3_{Guid.NewGuid().ToString("N")}",
                    ISBN4=$"ISBN4_{Guid.NewGuid().ToString("N")}",
                    ISBN5=$"ISBN5_{Guid.NewGuid().ToString("N")}",
                    ISBN6=$"ISBN6_{Guid.NewGuid().ToString("N")}",
                    ISBN7=$"ISBN7_{Guid.NewGuid().ToString("N")}",
                    ISBN8=$"ISBN8_{Guid.NewGuid().ToString("N")}",
                    ISBN9=$"ISBN9_{Guid.NewGuid().ToString("N")}",
                    ISBN10=$"ISBN10_{Guid.NewGuid().ToString("N")}",
                    ISBN11=$"ISBN11_{Guid.NewGuid().ToString("N")}",
                });
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var handler = PropertyChanged;
            if (handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                booksCollection=value;
                OnPropertyChanged(nameof(BooksCollection));
            }
        }

        private DelCommand exportAsPDFCommand;
        public DelCommand ExportAsPDFCommand
        {
            get
            {
                if(exportAsPDFCommand == null)
                {
                    exportAsPDFCommand=new DelCommand(ExportAsPDFCommandExecuted);
                }
                return exportAsPDFCommand;
            }
        }

        private void ExportAsPDFCommandExecuted(object? obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                ExportDataGridToPdf(dg, $"{DateTime.Now.ToString("yyyyMMdddHHmmss")}_{Guid.NewGuid().ToString("N")}.pdf");
            }
        }
    
        public void ExportDataGridToPdf(DataGrid dataGrid, string filename)
        {
            // Create a save file dialog if filename isn't provided
            if (string.IsNullOrEmpty(filename))
            {
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter = "PDF files (*.pdf)|*.pdf",
                    FileName = "DataGridExport.pdf"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    filename = saveFileDialog.FileName;
                }
                else
                {
                    return;
                }
            }

            // Create a FlowDocument
            FlowDocument doc = new FlowDocument
            {
                PageWidth = 1122, // 11 inches * 96 DPI
                PageHeight = 816, // 8.5 inches * 96 DPI
                PagePadding = new Thickness(50),
                ColumnGap = 0,
                ColumnWidth = double.MaxValue // Single column
            };

            // Create a Table in the FlowDocument
            Table table = new Table();
            doc.Blocks.Add(table);

            // Set up the columns
            for (int i = 0; i < dataGrid.Columns.Count; i++)
            {
                table.Columns.Add(new TableColumn());
            }

            // Add the header row
            TableRowGroup headerGroup = new TableRowGroup();
            table.RowGroups.Add(headerGroup);
            TableRow headerRow = new TableRow();
            headerGroup.Rows.Add(headerRow);

            foreach (DataGridColumn column in dataGrid.Columns)
            {
                headerRow.Cells.Add(new TableCell(new Paragraph(new Run(column.Header.ToString()))
                {
                    FontWeight = FontWeights.Bold,
                    Background = Brushes.LightGray,
                    BorderBrush = Brushes.Gray,
                    BorderThickness = new Thickness(1)
                }));
            }

            // Add the data rows
            TableRowGroup dataGroup = new TableRowGroup();
            table.RowGroups.Add(dataGroup);

            foreach (var item in dataGrid.Items)
            {
                TableRow row = new TableRow();
                dataGroup.Rows.Add(row);

                foreach (DataGridColumn column in dataGrid.Columns)
                {
                    var cellValue = column.GetCellContent(item);
                    string text = (cellValue is TextBlock) ? (cellValue as TextBlock).Text :
                                  (cellValue is CheckBox) ? ((CheckBox)cellValue).IsChecked.ToString() :
                                  cellValue?.ToString() ?? string.Empty;

                    var cell = new TableCell(new Paragraph(new Run(text))
                    {
                        FontSize = 10
                    });
                    cell.BorderBrush = Brushes.Gray;
                    cell.BorderThickness = new Thickness(1);
                    row.Cells.Add(cell);
                }
            }

            // Print to PDF
            PrintDialog printDialog = new PrintDialog();            
            if (printDialog.ShowDialog() == true)
            {
                // Set the printer to "Microsoft Print to PDF"
                printDialog.PrintQueue = new System.Printing.PrintQueue(
                    System.Printing.LocalPrintServer.GetDefaultPrintQueue().HostingPrintServer,
                    "Microsoft Print to PDF");

                // Set the output file
                printDialog.PrintTicket.OutputColor = System.Printing.OutputColor.Color;
                printDialog.PrintTicket.OutputQuality = System.Printing.OutputQuality.Normal;
                printDialog.PrintTicket.PageMediaSize = new System.Printing.PageMediaSize(
                    System.Printing.PageMediaSizeName.ISOA3);

                // Print the document
                ((IDocumentPaginatorSource)doc).DocumentPaginator.PageSize =
                    new Size(doc.PageWidth, doc.PageHeight);

                printDialog.PrintDocument(
                    ((IDocumentPaginatorSource)doc).DocumentPaginator,
                    "DataGrid Export");              
            }
        }
    }

    public class DelCommand : ICommand
    {
        private Action<object?> execute;
        private Predicate<object?> canExecute;
        public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute= canExecuteValue;
        }
        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested+=value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute==null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string ISBN1 { get; set; }
        public string ISBN2 { get; set; }
        public string ISBN3 { get; set; }
        public string ISBN4 { get; set; }
        public string ISBN5 { get; set; }
        public string ISBN6 { get; set; }
        public string ISBN7 { get; set; }
        public string ISBN8 { get; set; }
        public string ISBN9 { get; set; }
        public string ISBN10 { get; set; }
        public string ISBN11 { get; set; }
    }
}

 

posted @ 2025-08-03 22:04  FredGrit  阅读(18)  评论(0)    收藏  举报