Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 983743
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T04:54:25+00:00 2026-05-16T04:54:25+00:00

Does anyone know how I can do the equivalent XAML binding in code? <DataGrid

  • 0

Does anyone know how I can do the equivalent XAML binding in code?

<DataGrid ... >
    <DataGrid.Columns>
        <DataGridTextColumn 
            Binding="{Binding Description}"  <=== set in code **
        />
    </DataGrid.Columns>
</DataGrid>

Cheers,
Berryl

=== UPDATE ====

It looks like the method I have been looking for is DataGridColumn.GenerateElement

If so, then the focus of this question is now how to set the Binding correctly. The reason I want to do this code is that my grid has 7 columns that are identical visually and whose data can be known by an index.

So I want to be able to simplify the xaml by using a subclass DataGridTextColumn which has an index property, and just have:

<DataGrid ... >
    <DataGrid.Columns >
        <local:DayOfWeekColumn Index="0" />
        <local:DayOfWeekColumn Index="1" />
        ....
        <local:DayOfWeekColumn Index="7" />
    </DataGrid.Columns >
</DataGrid >

=== REVISED QUESTION ===

Assuming the Binding itself is logically and syntactically correct, what should the parameters to BindingOperations.SetBinding be??

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) {
        var activity = (ActivityViewModel)dataItem;
        var cellData = activity.Allocations[Index];
        var b = new Binding
                {
                    Source = cellData,
                    UpdateSourceTrigger = UpdateSourceTrigger.LostFocus,
                    Converter = new AllocationAmountConverter()
                };


        BindingOperations.SetBinding(??, ??, b);
        return ??;
    }

=== EDITS for ARAN =====

I am not overriding GenerateElement right now, but rather trying to get a static helper to set my binding for me. The helper is needed in any event to compensate for not being able to bind Header content in the current implementation of MSFT’s DataGrid.

Basically the idea is to catch the DC from the grid and use it as necessary on each of the columns, which in this case would be the Header content, cell style, and Binding. Here is the code:

public class TimesheetDataGridColumnContextHelper
{

    static TimesheetDataGridColumnContextHelper() {
        FrameworkElement.DataContextProperty.AddOwner(typeof (DataGridTextColumn));
        FrameworkElement.DataContextProperty.OverrideMetadata(
            typeof (DataGrid), 
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, OnDataContextChanged));
    }

    public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var grid = d as DataGrid;
        if (grid == null || !grid.Name.Equals("adminActivityGrid")) return;

        foreach (var col in grid.Columns) {

            var dowCol = col as DayOfTheWeekColumn;
            if (dowCol == null) continue;

            var context = (IActivityCollectionViewModelBase) e.NewValue;
            var index = Convert.ToInt32(dowCol.DowIndex);

            _setHeader(dowCol, context, index);

            var editStyle = (Style) grid.FindResource("GridCellDataEntryStyle");
            dowCol.CellStyle = editStyle;

            _setBinding(dowCol, index, context);

        }
    }

    private static void _setBinding(DayOfTheWeekColumn dowCol, int index, IActivityCollectionViewModelBase context) {
        dowCol.Binding = new Binding
                         {
                             Path = new PropertyPath(string.Format("Allocations[{0}]", index)),
                             UpdateSourceTrigger = UpdateSourceTrigger.LostFocus,
                             Converter = new AllocationAmountConverter()
                         };
    }

    private static void _setHeader(DataGridColumn col, IActivityCollectionViewModelBase context, int index)
    {
        var date = context.HeaderDates[index];
        var tb = new TextBlock
                 {
                     Text = date.ToString(Strings.ShortDayOfWeekFormat),
                     ToolTip = date.ToLongDateString()
                 };
        col.Header = tb;
    }

}

}

Everything works except for the Binding. I can’t tell if it’s because my binding is wrong somehow (although I get no obvious errors) or this is not a good place to set it. The grid columns are just empty when I run it.

Any idea??

Cheers,
Berryl

=== FIXED! ===

The logic in the last update was actually correct, but getting lost in the internals of the DataGrid I missed that my Binding.Path was missing the property to be bound to! Credit to Aran for understanding the issue, realizing that GenerateElement overrides were not necessary, and catching that the Binding Source should not have been set.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T04:54:26+00:00Added an answer on May 16, 2026 at 4:54 am

    You’re always doing the fiddly grid bits eh Beryl?

    Do a couple of things. Use reflector to look at the implementation of GenerateElement in the DataGridTextColumn. (.NET programmers live in reflector)

    Now for the answer:

    In the datagrid each column is not part of the visual tree. The column has two methods GenerateElement and GenerateEditingElement. These methods return the viewer and the editor for the cell respectively. In your method above you are not creating the viewer, which will probably be a TextBlock.

    from reflector, the implementation of GenerateElement is as below, notice the first thing they do is create the viewer for the cell.

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        TextBlock e = new TextBlock();
        this.SyncProperties(e);
        base.ApplyStyle(false, false, e);
        base.ApplyBinding(e, TextBlock.TextProperty);
        return e;
    }
    

    Once you have a textblock you can use the line below to set the binding on it.

    BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, binding);
    

    I am not however convinced that you actually need to override the GenerateElement and GenerateEditingElement to get your desired effect. I think you could overide the Binding property of the base class and just modify the binding there with your extra field whenever it is set. This will mean everything else will just work and you wont end up removing functionality from your column. Once again a crawl through reflector looking at the class DataGridBoundColumn (the abstract base class) would be beneficial.

    I do something similiar in one of our columns whenever a binding is set I modify the clipboard binding by adding an extra property so I can copy and paste effectively.

    EDIT: Update…this should probably be another question but..

    You are explicitly setting the source of the binding in your setBinding method. In the grid the source of the binding is the data contained in the row. You are setting it, which means it would be the same for each row. You can apply these funky bindings without the source property before the data context is set, the source becomes the item in each row, and your binding should reflect an index into the property held in each row.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 518k
  • Answers 518k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You can use the -Werror option with JDK 6. On… May 16, 2026 at 8:05 pm
  • Editorial Team
    Editorial Team added an answer Key events only fire on the document and elements that… May 16, 2026 at 8:05 pm
  • Editorial Team
    Editorial Team added an answer First set your bookmarklet with a link you can drop… May 16, 2026 at 8:05 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Does anyone know if there is a good equivalent to Java's Set collection in
Does anyone know how can I add an integer from another table to the
does anyone know if you can get individual field comments from mysql using Zend
Does anyone know if you can detect if headphones are plugged into the iPhone,
Does anyone know where I can get a list of BaseDefinitions for the ClassificationTypeDefitions
Does anyone know if there is a way to "transform" specific sections of values
I'm looking to do the equivalent of Python's inspect.getargspec() in Javascript. I do know
I'm attempting to import code written in linux into eclipse's perl plugin 'epic', and
I'm not English speaker, sorry in advance. I have a ColdFusion 6.1 application, and
I am fairly familiar with Autofac and one feature that I really love about

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.