Markus, here's what I would do. Bite the bullet and for the price of writing 10 lines of code get yourself a first class support for alignments and any other unsupported properties. you can traverse the visual tree and look up for PART_* thing for the heavy fine tunung.
The solution is:
1. Alignable Column Class:
namespace AlignableCellsProject
{
public class AlignableTextColumn: DataGridTextColumn
{
protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
FrameworkElement element = base.GenerateElement(cell, dataItem);
element.SetValue(FrameworkElement.HorizontalAlignmentProperty, this.HorizontalAlignment);
return element;
}
protected override System.Windows.FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
FrameworkElement element = base.GenerateEditingElement(cell, dataItem);
element.SetValue(FrameworkElement.HorizontalAlignmentProperty, this.HorizontalAlignment);
return element;
}
public HorizontalAlignment HorizontalAlignment
{
get { return (HorizontalAlignment)this.GetValue(FrameworkElement.HorizontalAlignmentProperty); }
set { this.SetValue(FrameworkElement.HorizontalAlignmentProperty, value); }
}
}
}
2. Consumer's XAML:
<Window x:Class="AlignableCellsProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:AlignableCellsProject"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="g" AutoGenerateColumns="False">
<DataGrid.Columns>
<local:AlignableTextColumn HorizontalAlignment="Left"
Width="200" Binding="{Binding}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
3 - Consumer's Code Behind:
namespace AlignableCellsProject
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded +=
(o, e) =>
{
this.g.ItemsSource = Enumerable.Range(1, 3);
};
}
}
}