Hi all,
I am trying to align the text of my columns dynamically so that means I cannot do anything in the xaml. I am using this piece of code that I found:
void datagrid_FieldLayoutInitialized(object sender, FieldLayoutInitializedEventArgs e) {
{
for (int i = 0; i < e.FieldLayout.Fields.Count; i++) {
Style myStyle = new Style(typeof(CellValuePresenter
)); myStyle.Setters.Add(
myStyle.Setters.Add(
new Setter(CellValuePresenter.HorizontalContentAlignmentProperty, HorizontalAlignment.Center ));
e.FieldLayout.Fields[i].Settings.CellValuePresenterStyle = myStyle;
} }
}
The problem is that the content itself is not aligned in the center. Number fields are aligned to the right and text fields to the left. What happens is when I click on a cell, the textbox to input the data is centered. Once I click out of the cell, it goes back to being aligned the way before. I need the data, both number and text fields, to be aligned center.
Any suggestions?
Any luck with this issue has I have still not been able to figure this out.
dejack2, the following code should work:
XAML:
<Grid.Resources>
<Style TargetType="{x:Type igEditors:XamTextEditor}" >
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
<Style TargetType="{x:Type igEditors:XamNumericEditor}" >
<Style TargetType="{x:Type igEditors:XamDateTimeEditor}" >
</Grid.Resources>
If you want to do this in C#, you can use the following example:
AddCenterStyle(this.XamDataGrid1,typeof(XamTextEditor));
AddCenterStyle(this.XamDataGrid1,typeof(XamNumericEditor));
AddCenterStyle(this.XamDataGrid1,typeof(XamDateTimeEditor));
void AddCenterStyle(Control c, Type t)
Style s = new Style(t);
s.Setters.Add(new Setter(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Center));
s.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
c.Resources.Add(t, s);
The AddCenterStyle is being called from the constructor after InitializeComponent() in this example.
Thanks, this is what I was looking for.
Hi,
Great that it works, I even use that solution myself when I need to align columns, but I have to say that it makes no sense to set the alignment on the editor instead of on the presenter.
Instead of having one style that can be shared between all the cells (of any type) that I want to be aligned to the left, I need to create a separate style per cell type (editor type) and set it to the cell.
Not only that, if my field type is dynamic, meaning I'm setting the cells EditAsType property in runtime I can't set the style of the cell in the xaml since I don't know what type of editor I'm going to use. so in that case it's even not usable.