Ketan Dubey Ketan Dubey - 1 month ago 8
C# Question

How to bind a ObservableCollection of type string to Datagrid

I have a rather simple query, I have a

ObservableCollection
of type
string
called Complaints. Now I would like to bind this
ObservableCollection
to a
DataGrid
with two columns: a checkbox template column, and
Complaint
column which contains the complaint. I would want to know how to achieve this? I'm using MVVM. I have set the
ItemsSource
property of the
DataGrid
to
Complaints
but cannot see the data as I do not know what to put in
Binding
for the second column of the
DataGrid
. How do I do this?


My View Model



public class MyViewModel() : INotifyPropertyChanged
{
private ObservableCollection<string> _complaints;

public ObservableCollection<string> Complaints
{
get
{
return _complaints;
}
set
{
_complaints = value;
NotifyPropertyChanged("Complaints");
}
}

}



My Datagrid


<DataGrid x:Name="dg_pc" ItemsSource="{Binding Path=Complaints}" Grid.Column="0">
<DataGrid.Columns>
//Checkbox Template Column.
<DataGridTemplateColumn Width="6.5217*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="cb_datagrid" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

//This is the column, where I need to display the **Complaint** Collection
<DataGridTextColumn Width="93.4782*"Header="Complaints" />
</DataGrid.Columns>
</DataGrid>

Answer Source

You need to set the Binding property of the DataGridTextColumn. This binding is relative to the data items of the source collection. Since your source collection itself is the item you want to display in the column, the binding will be to the item itself.

<DataGridTextColumn Width="93.4782*" Header="Complaints" Binding="{Binding}"/>

or equivalently:

<DataGridTextColumn Width="93.4782*" Header="Complaints" Binding="{Binding Path=.}"/>

Typically for a DataGrid you would be binding to a collection of objects with various properties you want to display each in a column, not just a collection of strings.

Model:

public class Complaint : INotifyPropertyChanged
{
    public bool IsActive { get; set; }
    public string Content { get; set; }
    ...
}

View Model:

public class ComplaintsViewModel
{
    public ObservableCollection<Complaint> Complaints { get; set; }
    ...
}

View:

<DataGrid ItemsSource="{Binding Complaints}">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Active" Binding="{Binding IsActive}"/>
        <DataGridTextColumn Header="Content" Binding="{Binding Content}"/>
    </DataGrid.Columns>
<DataGrid/>