问题描述
在使用WPF进行应用开发,使用DataGrid制表时总是在最后面有一个空列, 例如给定如下代码:
<DataGrid
Name="datagrid"
Grid.Row="1"
AlternatingRowBackground="Black"
HeadersVisibility="All">
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Gray" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="BorderBrush" Value="Black" />
<Setter Property="BorderThickness" Value="0,0,1,2" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn
Width="150"
Binding="{Binding Name}"
Header=" 名称 " />
<DataGridTextColumn
Width="150"
Binding="{Binding Type}"
Header=" 类型 " />
<DataGridTextColumn
Width="150"
Binding="{Binding Value}"
Header=" 描述 " />
</DataGrid.Columns>
</DataGrid>
界面显示为:
在最后面产生了一个空列,现希望去除该空列。
解决方案
其实这个“空列”并不是真的有一个列,而是整个表格被水平拉伸的缘故,解决方法也很简单,给表格加一个左对齐就好了:
<DataGrid
Name="datagrid"
Grid.Row="1"
AlternatingRowBackground="Black"
<!--添加这一句-->
HorizontalAlignment="Left"
HeadersVisibility="All">
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Gray" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="BorderBrush" Value="Black" />
<Setter Property="BorderThickness" Value="0,0,1,2" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn
Width="150"
Binding="{Binding Name}"
Header=" 名称 " />
<DataGridTextColumn
Width="150"
Binding="{Binding Type}"
Header=" 类型 " />
<DataGridTextColumn
Width="150"
Binding="{Binding Value}"
Header=" 描述 " />
</DataGrid.Columns>
</DataGrid>
效果如下图: