How to Align DatagridColumnHeader text depending on the Type of DataGridColumn

Edgar MWANDIRA 0 Reputation points
2023-05-14T13:59:34.27+00:00

Hello Guys,

I want a Style such that for WPF DataGridComboBoxColumn I want the DataGrid Header Text to be Left aligned and centered when it is not.

How can I do that without changing every column? i.e. a Style that can be applied to all and any Datagrid.

Developer technologies Windows Presentation Foundation
Developer technologies XAML
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. don bradman 621 Reputation points
    2023-05-15T03:58:45.25+00:00

    Try this (to apply this for all datagrid's throughout the app place it inside <Application.Resources> in the app.xaml file):

    <Style TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Column.DisplayIndex}" Value="0">
                <Setter Property="HorizontalContentAlignment" Value="Left"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
    
    

  2. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2023-05-24T06:44:28.9833333+00:00

    Hi,@Edgar MWANDIRA. Welcome Microsoft Q&A.

    For the problem of setting the title text of all DataGridComboBoxColumn to be left aligned, while other DataGrid columns should be centered, you could refer to the following code.

    <Window x:Class="DatagridColumnHeaderLeftaligned.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:DatagridColumnHeaderLeftaligned"
            xmlns:core="clr-namespace:System;assembly=mscorlib"  
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Window.Resources>
            <local:ColumnTypeConverter x:Key="ColumnTypeConverter"/>
            <Style  x:Key="CustomColumnHeaderStyle1" TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="HorizontalAlignment" Value="Center"/>
                <Setter Property="Background" Value="Transparent"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ColumnTypeConverter}}" Value="ComboBox">
                        <Setter Property="HorizontalAlignment" Value="Left"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <ObjectDataProvider x:Key="myEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
                <ObjectDataProvider.MethodParameters>
                    <x:Type Type="local:OrderStatus"/>
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </Window.Resources>
        <Window.DataContext>
            <local:ViewModel/>
        </Window.DataContext>
        <Grid>
            <DataGrid ItemsSource="{Binding MyData}"  AutoGenerateColumns="False" ColumnHeaderStyle="{StaticResource CustomColumnHeaderStyle1 }"
                    >
                <DataGrid.Columns>
                    <DataGridComboBoxColumn Header="Order Status" Width="180"  SelectedItemBinding="{Binding Status}" ItemsSource="{Binding Source={StaticResource myEnum}}" />
                    <DataGridTextColumn Header="Text Column" Width="150" Binding="{Binding Name}"/>
                
                </DataGrid.Columns>
            </DataGrid>
    
        </Grid>
    </Window>
    
    
    
    

    Codebedhind:

     public enum OrderStatus { None, New, Processing, Shipped, Received };
        public class ViewModel : INotifyPropertyChanged
        {
            private User selecedItme;
            public User SelecedItem
            {
                get { return selecedItme; }
                set
                {
                    if (selecedItme != value)
                    {
                        selecedItme = value;
                        OnPropertyChanged("SelecedItem");
                    }
                }
            }
            private ObservableCollection<User> myData = new ObservableCollection<User>();
            public ObservableCollection<User> MyData
            {
                get { return myData; }
                set
                {
                    if (myData != value)
                    {
                        myData = value;
                        OnPropertyChanged("MyData");
                    }
                }
            }
    
            public ViewModel()
            {
                MyData.Add(new User() { Id = 1, Name = "user1" });
                MyData.Add(new User() { Id = 2, Name = "user2" });
                MyData.Add(new User() { Id = 3, Name = "user3" });
                MyData.Add(new User() { Id = 5, Name = "user4" });
                MyData.Add(new User() { Id = 6, Name = "user5" });
    
            }
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string name = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }
        }
        public class ColumnTypeConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value is DataGridColumnHeader columnHeader)
                {
                    if (columnHeader.Column is DataGridComboBoxColumn)
                    {
                        return "ComboBox";
                    }
                }
    
                return "Other";
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
        public class User
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    

    The result:

    User's image


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.