简体   繁体   English

从代码背后格式化DataGridTextColumn

[英]format DataGridTextColumn from code-behind

Maybe, I think, things are too simple. 我认为,也许事情太简单了。 I have a datagrid, dynamically adding columns from code behind. 我有一个数据网格,从后面的代码动态添加列。 This works. 这可行。 Then I have columns with integer-values, which I would like to see right-aligned in the column, but it fails. 然后我有带有整数值的列,我希望在该列中右对齐,但是失败。 My Code is: 我的代码是:

    public List<List<int>> IntegerData { get; set; }................

            DataGridTextColumn textC = new DataGridTextColumn();
            textC.Header = ("Column");
            textC.Binding = new Binding(string.Format("[{0}]", i));    
            textC.Binding.StringFormat = "00000"; 

and at the end I have something like: 最后我有类似的东西:

            myDataGrid.Itemssource = IntegerData

With the textC.Binding.String.Format the problem is: (First: it seems, that the stringFormat-LIne correctly overloads the previous line) 使用textC.Binding.String.Format时,问题是:(首先:看来,stringFormat-LIne正确地重载了​​前一行)

Format "0" gives an integer "1" "2", which is correct. 格式“ 0”给出一个正确的整数“ 1”“ 2”。

Format "00000" gives "00001" "00002" "00003" which is correct for String-Format, but not, what I would like to have 格式“ 00000”给出“ 00001”“ 00002”“ 00003”,它对于字符串格式是正确的,但不是我想要的

BUT: 但:

Format "######" gives also "1" "2" .. and so on (left-aligned, no leading blanks) 格式“ ######”也给出“ 1”“ 2” ..,依此类推(左对齐,无前导空格)

Due to formatting-rules I would have expected (or hoped), that ##### is placeholder as described and the result is "bbbb1" , "bbbb2" right-aligned. 由于我曾期望(或希望)有格式化规则,因此#####是所描述的占位符,结果是“ bbbb1”,“ bbbb2”右对齐。 (b is here for blank!) (b在这里是空白!)

So Binding seems to deal correctly with the "00000" Format, but not with "######" Format. 因此,绑定似乎可以正确处理“ 00000”格式,但不能正确处理“ ######”格式。 Has anybody any idea or experience with that idea? 有任何想法或经验吗? (all other Bindings, I find in internet, are much more complicated) (我在互联网上发现所有其他绑定都更加复杂)

You can solve your problem by creating a style rather than formating the text in the cell. 您可以通过创建样式而不是设置单元格中文本的格式来解决问题。

first, create a style: 首先,创建样式:

Style style = new Style(typeof(DataGridCell));
style.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Right));

than assign the style to the column 而不是将样式分配给列

textC.CellStyle = style;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM