GridViewColumn CellTemplate Code Behind

10,662

Solution 1

As you are not using the count property in your DataTemplate you could just create the DataTemplate in xaml, then you know that whatever properties you set on the TextBox will be applied. Personally I would use a Datagrid and set it as read only. It gives you more flexibility for creating dynamic columns of specififc types.

Solution 2

If you use DisplayMemberBinding, CellTemplate will not be used.

You must remove the line DisplayMemberBinding and add the binding as part of the data template:

private static DataTemplate getDataTemplate(int count)
{
    DataTemplate template = new DataTemplate();
    FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
    factory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
    factory.SetBinding(TextBlock.TextProperty, new Binding(string.Format("[{0}]", count)));
    template.VisualTree = factory;

    return template;
}
Share:
10,662
t.smith.htc
Author by

t.smith.htc

Updated on June 16, 2022

Comments

  • t.smith.htc
    t.smith.htc almost 2 years

    I have a listView that I construct at run-time, i.e. the columns are not known at compile-time.

    I would like to apply a DataTemplate to the cells such that the TextAlignment property is TextAlignment.Right. When creating the columns:

    foreach (var col in dataMatrix.Columns)
    {
        gridView.Columns.Add(
            new GridViewColumn
            {
                Header = col.Name,
                DisplayMemberBinding = new Binding(string.Format("[{0}]", count)),
                CellTemplate = getDataTemplate(count),
            });
        count++;
    }
    
    private static DataTemplate getDataTemplate(int count)
    {
        DataTemplate template = new DataTemplate();
        FrameworkElementFactory factory = new FrameworkElementFactory(typeof(TextBlock));
        factory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
        template.VisualTree = factory;
    
        return template;
    }
    

    The sample code above does not work properly as the cell contents is still aligned to the left.

  • Fütemire
    Fütemire almost 2 years
    Since the user specifically asked how to do this in code behind, this should be the accepted answer.