简体   繁体   中英

WPF context bound DataGrid center cell contents

I have a DataGrid that has its ItemsSource property bound to a property in my viewmodel. That property is a list of objects and is dynamically set after a button press and the items in the DataGrid populate rightly and the columns are auto generated. However the contents of the cells are top-left aligned and all solutions to "How to center DataGrid cell contents" I found are only for a DataGrid with manually predefined columns, while mine are generated based on the properties of the class the objects in the property belong to.

How to center DataGrid cell contents, when columns are auto generated based on the class properties of the objects loaded into it?

You could create an ElementStyle , either in your XAML markup or programmatically, and then handle the AutoGeneratingColumn event for the DataGrid :

public partial class Window1 : Window
{
    private static readonly Style s_elementStyle;

    static Window1()
    {
        const string Xaml = "<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"TextBlock\">" +
            "<Setter Property=\"HorizontalAlignment\" Value=\"Center\" />" +
            "<Setter Property=\"VerticalAlignment\" Value=\"Center\" />" +
            "</Style>";

        s_elementStyle = XamlReader.Parse(Xaml) as Style;
    }

    public Window1()
    {
        InitializeComponent();
        dataGrid.AutoGeneratingColumn += dg_AutoGeneratingColumn
    }

    private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.Column is DataGridTextColumn textColumn)
            textColumn.ElementStyle = s_elementStyle;
    }
}

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