最近在做一个公司的WPF项目,使用DataGrid控件实现一个表格,由于自带样式不美观,便自己修改了DataGrid的样式,修改后发现列宽不能使用鼠标作用拖动来改变列宽大小。
问题代码:
<!--设置表头样式-->
<Setter Property="ColumnHeaderStyle">
<Setter.Value>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#3F4C5D"/>
<Setter Property="UseLayoutRounding" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<Border Width="50" Margin="-1,0" BorderBrush="#E9ECF1"
BorderThickness="1 0 0 1"
SnapsToDevicePixels="True" UseLayoutRounding="True">
<ContentPresenter Margin="5,0"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
解决方案:添加Thumb控件实现拖动效果
<!--设置表头样式-->
<Setter Property="ColumnHeaderStyle">
<Setter.Value>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#3F4C5D"/>
<Setter Property="UseLayoutRounding" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<!--<Border Width="50" Margin="-1,0"
BorderBrush="#E9ECF1" BorderThickness="1 0 0 1"
SnapsToDevicePixels="True" UseLayoutRounding="True">
<ContentPresenter Margin="5,0"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Border Grid.Column="0" BorderThickness="0,0,0,1"
BorderBrush="#E9ECF1">
<ContentPresenter Margin="5,0"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<Thumb Grid.Column="1"
x:Name="PART_RightHeaderGripper"
Cursor="SizeWE" Width="1" Height="25"
BorderThickness="1"
BorderBrush="#E9ECF1"
VerticalAlignment="Center"
HorizontalAlignment="Right"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
这样就可以实现鼠标拖动改变列宽大小啦。