I´m trying to change the horizontal column alignment of a databound DataGrid depending on the data type (e.g. Int32, float,..).
After searching the web for a simple example for ages I have learned, that DataTriggers via xaml should be the right option to do that. Is that right? If so, how would I implement the trigger?
I am quite new to WPF and have been using WindowsForms in the past. It can´t be that difficult to change the column orientation dependent on the data type? Any help is appreciated!
Ok, I´ve solved this from the code behind now. Maybe someone could give me a hint how I could solve this more elegantly using XAML? I´ve been searching the web for hours to find an example thats not too hard for someone who´s new to WPF and just didn´t find anything a was able to implement successfully.
Ok, here´s the code: Having a DataTable as DataSource I add the following:
foreach (DataColumn cc in table.Columns)
{
Type type = cc.DataType;
Style alignStyle = new Style(typeof(Microsoft.Windows.Controls.DataGridCell));
alignStyle.Setters.Add(new Setter(Microsoft.Windows.Controls.DataGridCell.VerticalAlignmentProperty, VerticalAlignment.Center));
var column = new Microsoft.Windows.Controls.DataGridTextColumn
{
Header = cc.ColumnName,
Binding = new Binding(cc.ColumnName)
};
if(type.Name=="Int32"){
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
column.Foreground = Brushes.Red;
column.CellStyle = alignStyle;
}
else if (type.Name == "DateTime")
{
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center));
column.Foreground = Brushes.Green;
column.Binding.StringFormat = "{0:dd.MM.yyyy}";
column.CellStyle = alignStyle;
}
else if (type.Name == "String")
{
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Left));
column.Foreground = Brushes.Blue;
column.CellStyle = alignStyle;
}
else if (type.Name == "Double")
{
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
column.Foreground = Brushes.Brown;
column.Binding.StringFormat = "{0:F3}";
column.CellStyle = alignStyle;
}
grids.Columns.Add(column);
}