简体   繁体   中英

How do I set alignment on DataGridTextColumn cell text using code

I'm trying to add DataGridTextColumn programmatically, and set some properties to present the text in cells. I don't want to use TemplateColumn as it requires double-tab to enter edit mode. I can't find code that would set alignment of the text. Anyone has any idea how to achieve this? Thanks in advance.

I tried so far:

Dim txt As New DataGridTextColumn()         
Dim c As New DataGridCell    
c.HorizontalAlignment = HorizontalAlignment.Center    
txt.CellStyle = c.Style

and

txt.SetValue(TextBox.HorizontalAlignmentProperty, HorizontalAlignment.Center)

and few others that I didn't keep track of.

Create a style, and then assign it to txt.CellStyle.

C# code :

Style s = new Style();
s.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Center));
txt.CellStyle = s;

Thanks for your help and I found the solution only with your guidance. Especially thanks to @AnjumSKhan

This worked for me:

    Dim txt As New DataGridTextColumn()
    Dim s As New Style
    s.Setters.Add(New Setter(TextBox.TextAlignmentProperty, TextAlignment.Right))
    txt.CellStyle = s

In your c# code you have to use the index of the column. Here are some examples to set the cell alignment:

    dataGrid.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Center;
    dataGrid.Columns[0].ItemStyle.VerticalAlign = VerticalAlign.Middle;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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