琪胤 發表於 2025-7-12 16:13:00

WPF开发中自定义DataGrid样式

<h1 id="实际开发中难免需要自己重写gatagrid样式以下是我写的一个新样式">实际开发中难免需要自己重写GataGrid样式,以下是我写的一个新样式:</h1>
<h2 id="1view界面样式如下">1.view界面样式如下:</h2>
<pre><code>&lt;Window x:Class="WPFDemoMVVM.View.DataGridView"
                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:WPFDemoMVVM.View"
                xmlns:hr="clr-namespace:WPFDemoMVVM.Helpers"
                xmlns:be="clr-namespace:WPFDemoMVVM.Behaviors"
                xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
                mc:Ignorable="d"
                Title="DataGridView" Height="600" Width="800"&gt;
        &lt;Window.Resources&gt;
                &lt;CollectionViewSource x:Key="view" Filter="CollectionViewSource_Filter"/&gt;


                &lt;!--datagrid样式--&gt;
                &lt;Style x:Key="DataGridStyleCommon" TargetType="DataGrid"&gt;
                        &lt;Setter Property="RowHeight" Value="40"/&gt;
                        &lt;Setter Property="Background"Value="#191D2A" /&gt;
                        &lt;Setter Property="BorderBrush"Value="{x:Null}" /&gt;
                        &lt;Setter Property="Foreground" Value="White"/&gt;
                        &lt;Setter Property="Opacity" Value="1"/&gt;
                        &lt;!--该属性指示是否允许用户调整列宽度--&gt;
                        &lt;Setter Property="CanUserResizeColumns"   Value="false" /&gt;
                        &lt;!--网格线颜色--&gt;
                        &lt;Setter Property="VerticalGridLinesBrush" Value="{x:Null}"/&gt;
                        &lt;Setter Property="IsReadOnly" Value="True"&gt;&lt;/Setter&gt;
                        &lt;Setter Property="HorizontalGridLinesBrush"&gt;
                                &lt;Setter.Value&gt;
                                        &lt;SolidColorBrush Color="#10FFFFFF" /&gt;
                                        &lt;!--网格透明度--&gt;
                                &lt;/Setter.Value&gt;
                        &lt;/Setter&gt;
                        &lt;!--&lt;Setter Property="VerticalGridLinesBrush"&gt;
               &lt;Setter.Value&gt;
                       &lt;SolidColorBrush Color="#FFEA8777" /&gt;
               &lt;/Setter.Value&gt;
       &lt;/Setter&gt;--&gt;
                        &lt;!--表格字段显示手动完成--&gt;
                        &lt;Setter Property="AutoGenerateColumns" Value="False"&gt;&lt;/Setter&gt;
                        &lt;!--隔行换色 --&gt;
                        &lt;Setter Property="AlternationCount" Value="3"&gt;&lt;/Setter&gt;
                        &lt;!--DataGrid控件模板--&gt;
                        &lt;Setter Property="Template"&gt;
                                &lt;Setter.Value&gt;
                                        &lt;ControlTemplate TargetType="{x:Type DataGrid}"&gt;
                                                &lt;Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" x:Name="border"
                                               Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True"&gt;
                                                        &lt;ScrollViewer x:Name="DG_ScrollViewer" Focusable="false"&gt;
                                                                &lt;ScrollViewer.Template&gt;
                                                                        &lt;ControlTemplate TargetType="{x:Type ScrollViewer}"&gt;
                                                                                &lt;Grid&gt;
                                                                                        &lt;Grid.ColumnDefinitions&gt;
                                                                                                &lt;ColumnDefinition x:Name="col_rowheader" Width="1" /&gt;
                                                                                                &lt;ColumnDefinition Width="*" /&gt;
                                                                                                &lt;ColumnDefinition Width="Auto" /&gt;
                                                                                        &lt;/Grid.ColumnDefinitions&gt;
                                                                                        &lt;Grid.RowDefinitions&gt;
                                                                                                &lt;RowDefinition Height="Auto" /&gt;
                                                                                                &lt;RowDefinition Height="*" /&gt;
                                                                                                &lt;RowDefinition Height="Auto" /&gt;
                                                                                        &lt;/Grid.RowDefinitions&gt;
                                                                                        &lt;!--选中所有行--&gt;
                                                                                        &lt;Button Command="ApplicationCommands.SelectAll" Focusable="False" Style="{DynamicResource {ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}}" Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type DataGrid}}}"&gt;
                                                                                                &lt;Button.Visibility&gt;
                                                                                                        &lt;Binding Path="HeadersVisibility" RelativeSource="{RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type DataGrid}}"&gt;
                                                                                                                &lt;Binding.ConverterParameter&gt;
                                                                                                                        &lt;DataGridHeadersVisibility&gt;All&lt;/DataGridHeadersVisibility&gt;
                                                                                                                &lt;/Binding.ConverterParameter&gt;
                                                                                                        &lt;/Binding&gt;
                                                                                                &lt;/Button.Visibility&gt;
                                                                                        &lt;/Button&gt;
                                                                                        &lt;!--表格头部--&gt;
                                                                                        &lt;DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter" Grid.Column="1" Grid.ColumnSpan="2"
                                                                                               Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" &gt;
                                                                                        &lt;/DataGridColumnHeadersPresenter&gt;
                                                                                        &lt;!--主数据区--&gt;
                                                                                        &lt;Grid Grid.Row="1" Grid.ColumnSpan="2"&gt;
                                                                                                &lt;ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" Grid.ColumnSpan="2" /&gt;
                                                                                        &lt;/Grid&gt;
                                                                                        &lt;!--垂直滑动条--&gt;

                                                                                        &lt;ScrollBar x:Name="PART_VerticalScrollBar" Grid.Column="2" Maximum="{TemplateBinding ScrollableHeight}"
                                                                                                Orientation="Vertical" Grid.Row="0" Grid.RowSpan="3" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
                                                                                                Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"
                                                                                                ViewportSize="{TemplateBinding ViewportHeight}" /&gt;

                                                                                        &lt;!--横向滑动条--&gt;
                                                                                        &lt;!--
                                                                       &lt;ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2"
                                                                                                        Maximum="{TemplateBinding ScrollableWidth}" Orientation="Horizontal"
                                                                                                        Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
                                                                                                        Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"
                                                                                                        ViewportSize="{TemplateBinding ViewportWidth}" /&gt;--&gt;
                                                                                &lt;/Grid&gt;
                                                                        &lt;/ControlTemplate&gt;
                                                                &lt;/ScrollViewer.Template&gt;
                                                                &lt;ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /&gt;
                                                        &lt;/ScrollViewer&gt;
                                                &lt;/Border&gt;
                                                &lt;ControlTemplate.Triggers&gt;
                                                        &lt;Trigger Property="IsEnabled" Value="false"&gt;
                                                                &lt;Setter Property="Opacity" Value="1" TargetName="border" /&gt;
                                                        &lt;/Trigger&gt;
                                                &lt;/ControlTemplate.Triggers&gt;
                                        &lt;/ControlTemplate&gt;
                                &lt;/Setter.Value&gt;
                        &lt;/Setter&gt;
                        &lt;Style.Triggers&gt;
                                &lt;Trigger Property="IsGrouping" Value="true"&gt;
                                        &lt;Setter Property="ScrollViewer.CanContentScroll" Value="false" /&gt;
                                &lt;/Trigger&gt;
                        &lt;/Style.Triggers&gt;

                &lt;/Style&gt;

                &lt;!--行头部样式--&gt;
                &lt;Style x:Key="DataGridRowHeaderStyleCommon" TargetType="DataGridRowHeader"&gt;
                        &lt;Setter Property="HorizontalContentAlignment" Value="Stretch" /&gt;
                        &lt;Setter Property="VerticalContentAlignment" Value="Center" /&gt;
                        &lt;Setter Property="Background" Value="Transparent" /&gt;
                        &lt;Setter Property="BorderBrush" Value="{x:Null}" /&gt;
                        &lt;Setter Property="BorderThickness" Value="1" /&gt;
                        &lt;Setter Property="Margin" Value="0,0,0,0" /&gt;
                        &lt;Setter Property="Template"&gt;
                                &lt;Setter.Value&gt;
                                        &lt;ControlTemplate TargetType="{x:Type DataGridRowHeader}"&gt;
                                                &lt;Grid&gt;
                                                        &lt;Border BorderBrush="{TemplateBinding BorderBrush}"
                                                        Background="{TemplateBinding Background}"
                                                        BorderThickness="{TemplateBinding BorderThickness}"
                                                        Padding="{TemplateBinding Padding}"
                                                        Margin="{TemplateBinding Margin}"
                                                        SnapsToDevicePixels="True"&gt;
                                                                &lt;ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                                                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                                                                  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/&gt;
                                                        &lt;/Border&gt;
                                                &lt;/Grid&gt;
                                        &lt;/ControlTemplate&gt;
                                &lt;/Setter.Value&gt;
                        &lt;/Setter&gt;
                &lt;/Style&gt;

                &lt;!--标题栏 列头部样式--&gt;
                &lt;Style x:Key="DataGridColumnHeaderStyleCommon" TargetType="DataGridColumnHeader"&gt;
                        &lt;Setter Property="SnapsToDevicePixels" Value="True" /&gt;
                        &lt;Setter Property="MinWidth" Value="15" /&gt;
                        &lt;Setter Property="MinHeight" Value="28" /&gt;
                        &lt;!--&lt;Setter Property="Foreground" Value="#FF0FA459" /&gt;--&gt;
                        &lt;Setter Property="Foreground" Value="{DynamicResource textBoxWhiteColor}" /&gt;
                        &lt;Setter Property="FontSize"   Value="14" /&gt;
                        &lt;!--&lt;Setter Property="Cursor"   Value="Hand" /&gt;--&gt;
                        &lt;Setter Property="Height" Value="30" /&gt;
                        &lt;Setter Property="Template"&gt;
                                &lt;Setter.Value&gt;
                                        &lt;ControlTemplate TargetType="DataGridColumnHeader"&gt;
                                                &lt;!--设置表头的背景等样式--&gt;
                                                &lt;Border x:Name="BackgroundBorder"Background="{DynamicResource backgroundGrayColor}"   BorderThickness="0"   BorderBrush="{DynamicResource borderBrushCommonColor}"Width="Auto"&gt;
                                                        &lt;Grid&gt;
                                                                &lt;Grid.ColumnDefinitions&gt;
                                                                        &lt;ColumnDefinition Width="*" /&gt;
                                                                &lt;/Grid.ColumnDefinitions&gt;
                                                                &lt;!--内容--&gt;
                                                                &lt;ContentPresenterMargin="0,0,0,0"VerticalAlignment="Center"HorizontalAlignment="Center" /&gt;
                                                                &lt;!--排序图标--&gt;
                                                                &lt;Path x:Name="SortArrow"Visibility="Collapsed"   Data="M0,0 L1,0 0.5,1 z"Stretch="Fill"    Grid.Column="2"   
                                                                   Width="8"Height="6"Fill="{DynamicResource textBoxWhiteColor}" Margin="0,0,50,0"VerticalAlignment="Center"RenderTransformOrigin="1,1" /&gt;
                                                                &lt;!--分割线--&gt;
                                                                &lt;Rectangle Visibility="Collapsed"Width="1" Fill="#d6c79b" HorizontalAlignment="Right"Grid.ColumnSpan="1"   /&gt;
                                                        &lt;/Grid&gt;
                                                &lt;/Border&gt;
                                        &lt;/ControlTemplate&gt;
                                &lt;/Setter.Value&gt;
                        &lt;/Setter&gt;
                &lt;/Style&gt;


                &lt;!--行样式触发--&gt;
                &lt;!--背景色改变必须先设置cellStyle 因为cellStyle会覆盖rowStyle样式--&gt;
                &lt;Style x:Key="DataGridRowStyleCommon"TargetType="DataGridRow"&gt;
                        &lt;Setter Property="Background"Value="#0D0D19"/&gt;
                        &lt;Setter Property="Height"Value="40" /&gt;
                        &lt;Setter Property="Foreground" Value="White" /&gt;
                        &lt;Style.Triggers&gt;
                                &lt;!--隔行换色--&gt;
                                &lt;!--&lt;Trigger Property="AlternationIndex"Value="0"&gt;
                        &lt;Setter Property="Background"   Value="{x:Null}" /&gt;
                &lt;/Trigger&gt;--&gt;
                                &lt;!--&lt;Trigger Property="AlternationIndex"   Value="1"&gt;
                        &lt;Setter Property="Background" Value="#FFD4C9F9" /&gt;
                &lt;/Trigger&gt;
                &lt;Trigger Property="AlternationIndex"   Value="2"&gt;
                        &lt;Setter Property="Background" Value="#FFFFCFC7" /&gt;
                &lt;/Trigger&gt;--&gt;
                                &lt;Trigger Property="IsMouseOver"   Value="True"&gt;
                                        &lt;Setter Property="Foreground" Value="White"/&gt;
                                        &lt;Setter Property="Background"Value="#191D2A" /&gt;
                                        &lt;Setter Property="Cursor" Value="Hand"/&gt;
                                        &lt;Setter Property="Opacity" Value="0.6"&gt;&lt;/Setter&gt;
                                &lt;/Trigger&gt;
                                &lt;Trigger Property="IsSelected" Value="True"&gt;
                                        &lt;!--&lt;Setter Property="Foreground"   Value="#FFF31006" /&gt;--&gt;
                                        &lt;Setter Property="Opacity" Value="1"&gt;&lt;/Setter&gt;
                                        &lt;Setter Property="Background" Value="#1D1D2A"/&gt;
                                &lt;/Trigger&gt;
                        &lt;/Style.Triggers&gt;
                &lt;/Style&gt;

                &lt;!--单元格样式触发--&gt;
                &lt;Style x:Key="DataGridCellStyleCommon" TargetType="DataGridCell"&gt;
                        &lt;Setter Property="Template"&gt;
                                &lt;Setter.Value&gt;
                                        &lt;ControlTemplate TargetType="DataGridCell"&gt;
                                                &lt;TextBlock TextAlignment="Center"VerticalAlignment="Center"&gt;   
                                        &lt;ContentPresenter /&gt;
                                                &lt;/TextBlock&gt;
                                        &lt;/ControlTemplate&gt;
                                &lt;/Setter.Value&gt;
                        &lt;/Setter&gt;
                        &lt;Style.Triggers&gt;
                                &lt;Trigger Property="IsSelected" Value="True"&gt;
                                        &lt;Setter Property="Foreground" Value="White" /&gt;
                                        &lt;Setter Property="FontWeight" Value="Bold"/&gt;
                                &lt;/Trigger&gt;
                                &lt;Trigger Property="IsMouseOver" Value="True"&gt;
                                        &lt;Setter Property="Foreground" Value="White"/&gt;
                                &lt;/Trigger&gt;
                        &lt;/Style.Triggers&gt;
                &lt;/Style&gt;

        &lt;/Window.Resources&gt;
        &lt;Grid&gt;
                &lt;Grid.RowDefinitions&gt;
                        &lt;RowDefinition/&gt;
                        &lt;RowDefinition Height="80"/&gt;
                &lt;/Grid.RowDefinitions&gt;
                &lt;StackPanel Grid.Row="0" Height="600" Orientation="Vertical"&gt;
                        &lt;Grid Width="auto"&gt;
                                &lt;DataGrid Name="userInfoGrid"AutoGenerateColumns="False" Height="360" HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalAlignment="Top" IsReadOnly="True" CanUserAddRows="False" VerticalScrollBarVisibility="Auto" EnableRowVirtualization="False"                                 
                                Style="{DynamicResource ResourceKey=DataGridStyleCommon}"
                                   RowHeaderStyle="{DynamicResource ResourceKey=DataGridRowHeaderStyleCommon}"                  
                                   ColumnHeaderStyle="{DynamicResource ResourceKey=DataGridColumnHeaderStyleCommon}"                  
                                   RowStyle="{DynamicResource ResourceKey=DataGridRowStyleCommon}"                  
                                   CellStyle="{DynamicResource ResourceKey=DataGridCellStyleCommon}" Margin="2 0 5 0" BorderThickness="1" ItemsSource="{Binding CollectionView,Mode=OneWay}"
                                                  hr:MultiSelectorHelper.MonitorSelectionChanged="True"
hr:MultiSelectorHelper.BindableSelectedItems="{Binding SelectedItems,Mode=OneWayToSource}"
                                                  &gt;

                                        &lt;i:Interaction.Behaviors&gt;
                                                &lt;be:SelectedItemsBehavior BindableSelectedItems="{Binding SelectedItems,Mode=OneWayToSource}"/&gt;
                                        &lt;/i:Interaction.Behaviors&gt;
                                        &lt;DataGrid.Columns&gt;
                                                &lt;DataGridTextColumn Binding="{Binding Id}" CanUserSort="False" IsReadOnly="True" Width="50"&gt;
                                                        &lt;DataGridTextColumn.HeaderTemplate&gt;
                                                                &lt;DataTemplate&gt;
                                                                        &lt;TextBlock Text="编号"/&gt;
                                                                &lt;/DataTemplate&gt;
                                                        &lt;/DataGridTextColumn.HeaderTemplate&gt;
                                                &lt;/DataGridTextColumn&gt;
                                                &lt;DataGridTextColumn Binding="{Binding Name}" CanUserSort="False" IsReadOnly="True" Width="*"&gt;
                                                        &lt;DataGridTextColumn.HeaderTemplate&gt;
                                                                &lt;DataTemplate&gt;
                                                                        &lt;TextBlock Text="账号名称"/&gt;
                                                                &lt;/DataTemplate&gt;
                                                        &lt;/DataGridTextColumn.HeaderTemplate&gt;
                                                &lt;/DataGridTextColumn&gt;
                                                &lt;DataGridTextColumn Binding="{Binding Salary}" CanUserSort="False" IsReadOnly="True" Width="*"&gt;
                                                        &lt;DataGridTextColumn.HeaderTemplate&gt;
                                                                &lt;DataTemplate&gt;
                                                                        &lt;TextBlock Text="金额"/&gt;
                                                                &lt;/DataTemplate&gt;
                                                        &lt;/DataGridTextColumn.HeaderTemplate&gt;
                                                &lt;/DataGridTextColumn&gt;
                                        &lt;/DataGrid.Columns&gt;
                                &lt;/DataGrid&gt;



                        &lt;/Grid&gt;
                &lt;/StackPanel&gt;
                &lt;StackPanel Grid.Row="1" Orientation="Horizontal"&gt;
                        &lt;!--&lt;TextBox x:Name="queryKeyword"Width="200" Height="50" TextChanged="queryKeyword_TextChanged"/&gt;--&gt;
                        &lt;TextBox x:Name="queryKeyword" Text="{Binding QueryKeyword,UpdateSourceTrigger=PropertyChanged}" Width="200" Height="50" /&gt;
                        &lt;Button Margin="5" Content="Add" Command="{Binding AddCommand}"/&gt;
                        &lt;Button Margin="5" Content="Calculate" Command="{Binding CalculateSumSalaryCommand}" CommandParameter="{Binding ElementName=userInfoGrid,Path=SelectedItems}"/&gt;

                &lt;/StackPanel&gt;

        &lt;/Grid&gt;
&lt;/Window&gt;
</code></pre>
<h2 id="2后台viewmodel类datagridviewmodel如下">2.后台ViewModel类DataGridViewModel如下:</h2>
<pre><code>public partial class DataGridViewModel :ObservableObject
{

        public List&lt;EmployeeModel&gt; employees;

       
        ICollectionView collectionView;

       
        string queryKeyword;

       
        IList selectedItems;


        partial void OnQueryKeywordChanged(string value) =&gt; CollectionView.Refresh();

        public DataGridViewModel()
        {
                IEnumerable&lt;EmployeeModel&gt; employees =EmployeeModel.FakeMany(5);
                this.employees = new List&lt;EmployeeModel&gt;(employees);
                CollectionView = CollectionViewSource.GetDefaultView(this.employees);
                CollectionView.Filter = (item) =&gt;
                {
                        if (string.IsNullOrEmpty(QueryKeyword)) return true ;
                        var em = item as EmployeeModel;
                        return em.Name.Contains(QueryKeyword,StringComparison.OrdinalIgnoreCase);
                };
        }

       
        public void Add()
        {
                employees.Add(EmployeeModel.FakeOne());
                CollectionView.Refresh();
        }

        //
        //public void CalculateSumSalary(IList employ)
        //{
        //    var sum = employ.Cast&lt;EmployeeModel&gt;().Sum(x =&gt; ((EmployeeModel)x).Salary);
        //}

       
        public void CalculateSumSalary()
        {
                if (SelectedItems != null)
                {
                        var sum = SelectedItems.Cast&lt;EmployeeModel&gt;().Sum(x =&gt; ((EmployeeModel)x).Salary);
                }

                foreach (var item in employees)
                {
                        item.IsSelected = item.Salary &gt; 15000;
                }
                collectionView.Refresh();
        }

}
</code></pre>
<h2 id="3效果图如下">3.效果图如下:</h2>
<p><img src="https://img2024.cnblogs.com/blog/2212230/202507/2212230-20250712161324948-1437679963.png"></p>
<p><strong>如果本文介绍对你有帮助,可以一键四连:点赞+评论+收藏+推荐,谢谢!</strong></p><br><br>
来源:https://www.cnblogs.com/chenshibao/p/18980713
頁: [1]
查看完整版本: WPF开发中自定义DataGrid样式