Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / WPF
Tip/Trick

Change WPF DataGrid Styles in Code Behind

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Nov 2014CPOL2 min read 23.9K   319   2   1
Change WPF DataGrid Styles in code behind

Introduction

In this tip, I am trying to find a way to write WPF applications by pure C# code for dynamically producing UI element and doing more Logic control in C# code. In this demo code, I used Virtual Studio to create a normal WPF application and then produce UI elements by C# code. A sample application is available within the zip files.

Background

In my daily work, I usually need to deal with a lot of data(DataGrid) and UI logic process at runtime application. In traditional C#, we could do this work perfectly, but in UI design is not so attractive. And then the WPF appears. But since WPF documents usually provide XAML sample code let UI designers to build up a lot of attractive components in design time. How about the run time process to do the same thing? How could we control the UI elements when data was dynamic load into application? So, I made this demo application to answer the above questions.

Using the Code

SetStyleFBColor

The SetStyleFBColor function is to build up a Style class which could apply on UI element. Although Microsoft has provided many DependencyProperty to setup a Style, but in this demo I only use ForegroundProperty and BackgroundProperty to change the UI elements colors.

C#
// <summary>
// This Function is for set styles foreground and background color by Input Controls type
// </summary>
// <param name="controlType">UI control to setup Foreground and background color</param>
// <param name="foreColor"></param>
// <param name="backColor"></param>
// <returns></returns>
Style SetStyleFBColor(Type controlType, Brush foreColor, Color backColor)
{
    Style subStyle;
    DependencyProperty dp, dp2, dp3;
    LinearGradientBrush linearBrush = null;
    //Init a Linear Brush
    InitLinearGradientBrush(ref linearBrush, backColor);
    //Setup Style property.
    Style aStyle = new Style(controlType);
    dp = GetDependencyPropertyByName(controlType, "ForegroundProperty");
    aStyle.Setters.Add(new Setter(dp, foreColor));
    dp2 = GetDependencyPropertyByName(controlType, "BackgroundProperty");
    aStyle.Setters.Add(new Setter(dp2, linearBrush));
    if (controlType.Name == "ComboBox")
    {
        //ComboBox has a sub style for setting up ComboboxItems.
        subStyle = new Style();
        subStyle.TargetType = typeof(ComboBoxItem);
        subStyle.Setters.Add(new Setter(ComboBoxItem.ForegroundProperty, foreColor));
        subStyle.Setters.Add(new Setter(ComboBoxItem.BackgroundProperty, linearBrush));
        dp3 = GetDependencyPropertyByName(controlType, "ItemContainerStyleProperty");
        aStyle.Setters.Add(new Setter(dp3, subStyle));
    }
    return aStyle;
}

Dynamic Produce DataGrid

In this code, I dynamically produce the datagrid UI element and using combobox as column style and bind data to System.Data.DataTable.

C#
// <summary>
// This function is to Demo how to create and fill combobox style DataGrid.
// </summary>
void FillDataGrid()
{
    WPFDataGrid.AutoGenerateColumns = false;
    WPFDataGrid.CanUserAddRows = false;
    WPFDataGrid.Columns.Clear();
    DataGridComboBoxColumn dgCbx;
    foreach (DataColumn dc in dt.Columns)
    {
        dgCbx = new DataGridComboBoxColumn();
        dgCbx.Header = dc.ColumnName;
        dgCbx.ItemsSource = selLst;
        //This is most important step to bind data to DataGridComboBoxColumn.
        dgCbx.TextBinding = new Binding(dc.ColumnName);
        dgCbx.CanUserSort = false;
        dgCbx.CanUserResize = false;
        dgCbx.CanUserReorder = false;
        WPFDataGrid.Columns.Add(dgCbx);
    }
    WPFDataGrid.ItemsSource = dt.DefaultView;
}

Reference

I have used some code from many contributors on the internet and some MSDN documents list as follows:

  1. Get DependencyProperty by Name for WPF and Silverlight

    http://www.infragistics.com/community/blogs/blagunas/archive/2013/01/29/get-dependencyproperty-by-name-for-wpf-and-silverlight.aspx

  2. Style and template MSDN

    http://msdn.microsoft.com/en-us/library/ms745683%28v=vs.85%29.aspx

  3. Create Dynamic DataGrid Column With Style and Trigger in WPF

    http://www.c-sharpcorner.com/UploadFile/87b416/dynamically-create-datagrid-column-with-style-and-trigger/

History

  • November 21, 2014 - First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Taiwan Taiwan
I am a Nobody but like use any programing skill to solve questions.
Also, like to share any ideas which could help other folks.

Comments and Discussions

 
PraiseUsing this code I was finally able to modify column headers in a WPF autogenerated DataGrid Pin
K)Hispanico9-May-18 7:00
K)Hispanico9-May-18 7:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.