在WPF DataGrid中删除空白列

24

我在WPF(C#)中使用DataSet来填充DataGrid。结果如下:

enter image description here

我想要移除左侧的空白列,并希望剩余的空间分配给其他列。期望的结果是:

enter image description here

我的XAML代码是:

<Window x:Class="RFID.CareerWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CareerWindow" Height="356" Width="404">
    <Grid>

        <DataGrid x:Name="dg1" HorizontalAlignment="Left" Margin="25,10,0,0" VerticalAlignment="Top" Height="306" Width="355" EnableRowVirtualization="false" EnableColumnVirtualization="false" FontFamily="2  badr" FontSize="20" FlowDirection="RightToLeft" CanUserAddRows="False" CanUserReorderColumns="False"/>

    </Grid>
</Window>
3个回答

50

避免设置固定的高度和宽度。

使用 ColumnWidth="*" 来共享DataGridColumns之间的空间

<DataGrid x:Name="dg1" ColumnWidth="*"
          HorizontalAlignment="Left" VerticalAlignment="Top" Margin="25,10,0,0"
          EnableRowVirtualization="false" EnableColumnVirtualization="false" 
          FontFamily="2  badr" FontSize="20" FlowDirection="RightToLeft" 
          CanUserAddRows="False" CanUserReorderColumns="False" />

它完美地工作了!谢谢!现在,你能帮我将所有文本(单元格和标题)对齐到中心吗? - Babak.Abad
2
请查看此SO帖子以对齐单元格文本。https://dev59.com/zFDTa4cB1Zd3GeqPH0md - Nitesh
1
这是一个关于如何在XAML中对齐DataGrid列标题内容的SO帖子。https://dev59.com/tWoy5IYBdhLWcg3wCpvQ - Nitesh
1
“HorizontalAlignment =” Left “是让它对我有用的东西。” - jsirr13
我赞同@jsirr13的意见,设置对齐方式有效,而将宽度设置为较小值会使所有列变得非常狭窄。 - Steve

3
你可以使用Grid的最后一列或其中一列设置。
<DataGridTextColumn Header="Surname"
                    Width="*"
                    Binding="{Binding Path=Surname,Mode=TwoWay}" IsReadOnly="True">
  <DataGridTextColumn.ElementStyle>
    <Style TargetType="TextBlock">
      <Setter Property="HorizontalAlignment" Value="Left" />
      <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
  </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

0

为了消除自动添加的列,请将 DataGridTextColumnWidth 设置为 *

以下代码表示一个具有两列且没有自动添加列的 DataGrid

<DataGrid AutoGenerateColumns="False" HeadersVisibility="Column">
 <DataGrid.Columns>
  <DataGridTextColumn Width="*" Binding="{Binding asdf}" />
  <DataGridTextColumn Width="*" Binding="{Binding zuio}" />     
 </DataGrid.Columns>
</DataGrid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接