Search code examples
c#wpfxamldatagridwpfdatagrid

Binding custom object list data to a Data Grid


Im trying to Bind a Custom data list to a Datagrid in WPF

This is the custom object:

public class User
{
    public string Name { get; set; }
    public string Role{ get; set; }
}

From the data base I fetch this data as a list

public List<User> allUsers;

I send this list to the view Model class ->

public ListWindowViewModel(object dataSource)
{
     this.datasource = dataSource;
}

public DataView GridData
{       
    get
    {
        DataSet ds = new DataSet("ListData");    
        ds = dataSource as DataSet;    
        return ds.Tables[0].DefaultView;
    }
 }

Inside my ListView xaml file I used binding ->

<DataGrid Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="5" Margin="3" x:Name="mainGrid"
                  ItemsSource="{Binding Path=GridData, Mode=OneWay}">
        </DataGrid>

Its not working becase the ds = dataSource as DataSet; is not working.


Solution

  • you can directly Create the collection like.

     private ObservableCollection<User> _allUsers=new ObservableCollection<User>();
    
        public ObservableCollection<User> allUsers
        {
            get { return _allUsers; }
            set { _allUsers = value; }
        }
    

    and your datagrid Binding look like

    <DataGrid Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="5" Margin="3" x:Name="mainGrid"
                  ItemsSource="{Binding=allUsers, Mode=OneWay}">
        </DataGrid>