Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGrid AutoGenerateColumns="True" - how to append one extra column?

Tags:

c#

wpf

datagrid

I'm using DataGrid with AutoGenerateColumns="True". Now in addition to auto-generated columns I want to add one my "custom" column, so called "service" column. (in it I want to have several hyperlinks "Start" "Stop" "Reset").

How to add addition column?

I found this page http://msdn.microsoft.com/ru-ru/library/system.windows.controls.datagrid.autogeneratecolumns.aspx that describes how to modify or remove column, but I can not find how to add column.

like image 630
Oleg Vazhnev Avatar asked Nov 22 '11 20:11

Oleg Vazhnev


2 Answers

You should be able to add a column in your designer like always. It'll just append that column to all the generated ones.

EDIT

Sorry, I assumed WinForms. Same idea though, just add the columns directly to the XAML:

    <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Src}" x:Name="Grid">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Header="Junk"></DataGridCheckBoxColumn>
            <DataGridHyperlinkColumn Header="Junk2"></DataGridHyperlinkColumn>
        </DataGrid.Columns>
    </DataGrid>

Here's the ViewModel:

public class ViewModel
{
    public ViewModel()
    {
        Src = new ObservableCollection<Item>() { new Item { Id = 1, Name = "A" }, new Item { Id = 2, Name = "B" } };
    }

    public ObservableCollection<Item> Src { get; set; }
}

public class Item{
    public int Id { get; set; }
    public string Name { get; set; }
}

And here's what it shows:

enter image description here

like image 61
Adam Rackis Avatar answered Oct 26 '22 08:10

Adam Rackis


You can either add it in XAML using <DataGrid.Columns> or you can do it in code.

Bear in mind that if you do it in XAML, by default it's going to put column at the beginning of the columns, i.e. before they're generated.

Alternatively, you can add it in code and specifically use the event AutoGeneratedColumns and and the code there and it will show up as the last column.

like image 3
Chris E Avatar answered Oct 26 '22 09:10

Chris E