WPF DataGrid 中的文本对齐方式
如何在 WPF DataGrid
中将列数据对齐到中心?
How can I align the column data to center in a WPF DataGrid
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何在 WPF DataGrid
中将列数据对齐到中心?
How can I align the column data to center in a WPF DataGrid
?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(13)
如果您使用 DataGridTextColumn,则可以使用以下代码片段:
If you are using DataGridTextColumn you can use the following code snippet:
在不了解具体情况的情况下很难说,但这里有一个居中的
DataGridTextColumn
:It's hard to say without knowing specifics, but here's a
DataGridTextColumn
that is centered:我从 huttelihut 的解决方案开始。 不幸的是,这对我来说还不起作用。 我调整了他的答案并提出了这个(解决方案是将文本向右对齐):
如您所见,我将样式应用于 TextBlock,而不是 DataGridCell。
然后我必须设置 Element 样式,而不是 Cell 样式。
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):
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.
肯特·布加特+1。
我最终这样做了,这使得代码稍微不那么混乱(并且使我能够在多个列上使用对齐方式):
+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):
这是 @MohammedAFadil 的 XAML 答案,转换为后面的 C# 代码:
要应用
Style
,请设置DataGrid
的CellStyle
属性,例如Here's @MohammedAFadil's XAML answer, converted to C# code behind:
To apply the
Style
, set theCellStyle
property of theDataGrid
, e.g.或者在后面的代码中:
Or in code behind:
我最终遇到了单元格移动的问题,并且使用接受的答案看起来很时髦。 我知道已经晚了,但希望我的发现能对某人有所帮助。 我用:
而不是单元格样式。
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:
rather than the CellStyle.
如果有人仍在寻找这个问题的答案,这对我有用:
If someone is still looking for answer for this, here's what worked for me:
对我来说这个效果很好
For me this one works well
好的,我使用了 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!
我最喜欢的解决方案是:
My favorite solution is:
感谢 Danny Beckett 将 @MohammedAFadil 的 XAML 答案转换为 C# 代码。 我的所有数据网格都是动态设置的,因此我可以随时更改任何内容。
要设置一个空的数据网格,其中没有任何内容,然后将其绑定到数据,只需使用 datagrid.columns
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
我真的很喜欢 Bruno 的 TextBlock.TextAlignment 方法。 您可以将其与水平对齐结合使用,然后任何背景都会延伸到整个网格单元。
例如(在VB中)
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)