WPF DataGrid 中的文本对齐方式

发布于 2024-07-16 15:21:02 字数 48 浏览 5 评论 0原文

如何在 WPF DataGrid 中将列数据对齐到中心?

How can I align the column data to center in a WPF DataGrid?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

画离情绘悲伤 2024-07-23 15:21:03

如果您使用 DataGridTextColumn,则可以使用以下代码片段:

<Style TargetType="DataGridCell">
     <Style.Setters>
            <Setter Property="TextBlock.TextAlignment" Value="Center" />
     </Style.Setters>
</Style>

If you are using DataGridTextColumn you can use the following code snippet:

<Style TargetType="DataGridCell">
     <Style.Setters>
            <Setter Property="TextBlock.TextAlignment" Value="Center" />
     </Style.Setters>
</Style>
甜味拾荒者 2024-07-23 15:21:03

在不了解具体情况的情况下很难说,但这里有一个居中的 DataGridTextColumn

<wpf:DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True">
    <wpf:DataGridTextColumn.CellStyle>
        <Style>
            <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
        </Style>
    </wpf:DataGridTextColumn.CellStyle>
</wpf:DataGridTextColumn>

It's hard to say without knowing specifics, but here's a DataGridTextColumn that is centered:

<wpf:DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True">
    <wpf:DataGridTextColumn.CellStyle>
        <Style>
            <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
        </Style>
    </wpf:DataGridTextColumn.CellStyle>
</wpf:DataGridTextColumn>
黑寡妇 2024-07-23 15:21:03

我从 huttelihut 的解决方案开始。 不幸的是,这对我来说还不起作用。 我调整了他的答案并提出了这个(解决方案是将文本向右对齐):

<Resources>
    <Style x:Key="RightAligned" TargetType="TextBlock">
        <Setter Property="HorizontalAlignment" Value="Right"/>
    </Style>
</Resources>

如您所见,我将样式应用于 TextBlock,而不是 DataGridCell。

然后我必须设置 Element 样式,而不是 Cell 样式。

ElementStyle="{StaticResource RightAligned}"

I started with huttelihut's solution. Unfortunately, that didn't work for me just yet. I tweaked his answer and came up with this (solution is to align the text to the right):

<Resources>
    <Style x:Key="RightAligned" TargetType="TextBlock">
        <Setter Property="HorizontalAlignment" Value="Right"/>
    </Style>
</Resources>

As you can see, I applied the style to a TextBlock, not the DataGridCell.

And then I had to set the Element style, not the Cell style.

ElementStyle="{StaticResource RightAligned}"
你爱我像她 2024-07-23 15:21:03

肯特·布加特+1。
我最终这样做了,这使得代码稍微不那么混乱(并且使我能够在多个列上使用对齐方式):

<Resources>
      <Style x:Key="NameCellStyle" TargetType="DataGridCell">
                <Setter Property="HorizontalAlignment" Value="Center" />
      </Style>
</Resources>


<DataGrid.Columns>                           
   <DataGridTextColumn Header="Name" CellStyle="{StaticResource NameCellStyle}" Binding="{Binding Name}"/>                            
    // .. other columns        
</DataGrid.Columns>

+1 for Kent Boogaart.
I ended up doing this, which makes the code slightly less cluttered (and enables me to use the alignment on several columns):

<Resources>
      <Style x:Key="NameCellStyle" TargetType="DataGridCell">
                <Setter Property="HorizontalAlignment" Value="Center" />
      </Style>
</Resources>


<DataGrid.Columns>                           
   <DataGridTextColumn Header="Name" CellStyle="{StaticResource NameCellStyle}" Binding="{Binding Name}"/>                            
    // .. other columns        
</DataGrid.Columns>
随风而去 2024-07-23 15:21:03

这是 @MohammedAFadil 的 XAML 答案,转换为后面的 C# 代码:

var MyStyle = new Style(typeof(DataGridCell)) {
    Setters = {
        new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center)
    }
};

要应用 Style,请设置 DataGridCellStyle 属性,例如

var MyGrid = new DataGrid() {
    CellStyle = MyStyle
};

Here's @MohammedAFadil's XAML answer, converted to C# code behind:

var MyStyle = new Style(typeof(DataGridCell)) {
    Setters = {
        new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center)
    }
};

To apply the Style, set the CellStyle property of the DataGrid, e.g.

var MyGrid = new DataGrid() {
    CellStyle = MyStyle
};
眼泪淡了忧伤 2024-07-23 15:21:03

或者在后面的代码中:

grid.CellStyle = newCellStyle();

public static Style newCellStyle()
{
    //And here is the C# code to achieve the above
    System.Windows.Style style = new Style(typeof(DataGridCell));
    style.Setters.Add(new System.Windows.Setter
    {
        Property = Control.HorizontalAlignmentProperty,
        Value = HorizontalAlignment.Center
    });
    return style;
}

Or in code behind:

grid.CellStyle = newCellStyle();

public static Style newCellStyle()
{
    //And here is the C# code to achieve the above
    System.Windows.Style style = new Style(typeof(DataGridCell));
    style.Setters.Add(new System.Windows.Setter
    {
        Property = Control.HorizontalAlignmentProperty,
        Value = HorizontalAlignment.Center
    });
    return style;
}
日暮斜阳 2024-07-23 15:21:03

我最终遇到了单元格移动的问题,并且使用接受的答案看起来很时髦。 我知道已经晚了,但希望我的发现能对某人有所帮助。 我用:

<DataGridTextColumn.ElementStyle>
     <Style>
          <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
     </Style>

而不是单元格样式。

I ended up having problems with the cell being shifted and looking funky using the accepted answer. I know it's late, but hopefully my findings will help someone. I use:

<DataGridTextColumn.ElementStyle>
     <Style>
          <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
     </Style>

rather than the CellStyle.

凡尘雨 2024-07-23 15:21:03

如果有人仍在寻找这个问题的答案,这对我有用:

<DataGridTextColumn ...>
    <DataGridTextColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Left"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

If someone is still looking for answer for this, here's what worked for me:

<DataGridTextColumn ...>
    <DataGridTextColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Left"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>
无悔心 2024-07-23 15:21:03

对我来说这个效果很好

<DataGridTextColumn Width="1*" Binding="{Binding Balance, StringFormat=C} "Header="Balance">
  <DataGridTextColumn.CellStyle>
      <Style>
        <Setter Property="TextBlock.TextAlignment"  Value="Right"/>
      </Style>
   </DataGridTextColumn.CellStyle>
 </DataGridTextColumn>

For me this one works well

<DataGridTextColumn Width="1*" Binding="{Binding Balance, StringFormat=C} "Header="Balance">
  <DataGridTextColumn.CellStyle>
      <Style>
        <Setter Property="TextBlock.TextAlignment"  Value="Right"/>
      </Style>
   </DataGridTextColumn.CellStyle>
 </DataGridTextColumn>
梦一生花开无言 2024-07-23 15:21:03

好的,我使用了 FrameworkElement 方法,但是当您尝试突出显示该行时,出现了奇怪的行为。

我在此 线程<中放置了 WPF Datagrid 对齐的另一个示例< /a>!

Ok, I used the frameworkElement approach but there was a strange behavior when you try to highlight the row.

I've put another example of WPF Datagrid alignment in this thread!

随心而道 2024-07-23 15:21:03

我最喜欢的解决方案是:

<DataGridTextColumn Header="My Column" Binding="{Binding MyDBValue}" Width="100" >
<DataGridTextColumn.CellStyle>
        <Style>
                <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
        </Style>
</DataGridTextColumn.CellStyle>

My favorite solution is:

<DataGridTextColumn Header="My Column" Binding="{Binding MyDBValue}" Width="100" >
<DataGridTextColumn.CellStyle>
        <Style>
                <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
        </Style>
</DataGridTextColumn.CellStyle>

﹂绝世的画 2024-07-23 15:21:03

感谢 Danny Beckett 将 @MohammedAFadil 的 XAML 答案转换为 C# 代码。 我的所有数据网格都是动态设置的,因此我可以随时更改任何内容。

要设置一个空的数据网格,其中没有任何内容,然后将其绑定到数据,只需使用 datagrid.columns

        var centerTextSetter = new Style(typeof(DataGridCell))
        {
            Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) }
        };
        DgDbNames.Columns.Add(new DataGridTextColumn()
        {
            Header = "Db Name",
            Binding = new System.Windows.Data.Binding("DbName"),
            IsReadOnly = true,
            Width = new DataGridLength(0.2, DataGridLengthUnitType.Star),
            CellStyle = centerTextSetter
        });

Thanks Danny Beckett for converting @MohammedAFadil's XAML answer, converted to C# code. All of my datagrids are set up dynamically, so I can change anything, whenever.

To set up an empty datagrid, with nothing in it and then just bind it to data, just take your datagrid.columns

        var centerTextSetter = new Style(typeof(DataGridCell))
        {
            Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) }
        };
        DgDbNames.Columns.Add(new DataGridTextColumn()
        {
            Header = "Db Name",
            Binding = new System.Windows.Data.Binding("DbName"),
            IsReadOnly = true,
            Width = new DataGridLength(0.2, DataGridLengthUnitType.Star),
            CellStyle = centerTextSetter
        });
寒尘 2024-07-23 15:21:03

我真的很喜欢 Bruno 的 TextBlock.TextAlignment 方法。 您可以将其与水平对齐结合使用,然后任何背景都会延伸到整个网格单元。

例如(在VB中)

    Dim sty = New System.Windows.Style(GetType(DataGridCell))
    sty.Setters.Add(New Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch))
    sty.Setters.Add(New Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right))
    sty.Setters.Add(New Setter(BackgroundProperty, Brushes.LightGray))

I really like Bruno's TextBlock.TextAlignment approach. You can use this in conjunction with horizontal alignment and then any background will stretch across the whole grid cell.

e.g. (in VB)

    Dim sty = New System.Windows.Style(GetType(DataGridCell))
    sty.Setters.Add(New Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch))
    sty.Setters.Add(New Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right))
    sty.Setters.Add(New Setter(BackgroundProperty, Brushes.LightGray))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文