Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView Column binding in WPF

I want to design a DataGrid as shown in the picture below:

enter image description here

I am planning to bind the DataGrid to list of objects of a class. The class I was planning is

class Class1
{
    public Int32 Index { get; set; }
    public string Colour { get; set; }
    public string Location { get; set; }
    public string Srno { get; set; }
}

I have a problem. I would like to have one more colour property which I can bind directly to the colour of the DataGrid in column2. But since I am planning to set DataGrid binding to list of this object, the new property will be recognized as a column itself. How do I avoid that? Any suggetions.

like image 470
user1687824 Avatar asked Feb 20 '14 04:02

user1687824


2 Answers

You can set AutoGenerateColumns to False and take responsibility in your hand to provide the list of columns you want to avoid auto generation of columns when DataSource or DataMember properties are set.

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding SourceCollection}">
  <DataGrid.Columns>
     <DataGridTextColumn Binding="{Binding Index}"/>
     <DataGridTextColumn Binding="{Binding Colour}"/>
     <DataGridTextColumn Binding="{Binding Location}"/>
     <DataGridTextColumn Binding="{Binding Srno}"/>
  </DataGrid.Columns>
</DataGrid>
like image 77
Rohit Vats Avatar answered Sep 23 '22 00:09

Rohit Vats


<DataGrid  Name="DataGrid1" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Index" Binding="{Binding Path=Index}" />
                    <DataGridTextColumn Header="Colour" Binding="{Binding Path=Colour}"/>
                    <DataGridTextColumn Header="Location" Binding="{Binding Path=Location}" />
                    <DataGridTextColumn Header="Srno" Binding="{Binding Path=Srno}" />
                </DataGrid.Columns>
            </DataGrid>

This is how you would do it, if you set the Datagrid1.ItemsSource = a List of Class1, like so.

 List<Class1> myList = new List<Class1>();
 DataGrid1.ItemsSource = myList;

Hope this helps.

like image 45
Max Mazur Avatar answered Sep 22 '22 00:09

Max Mazur