Search code examples
c#wpfdatagrid

How to bind a primitive type list to a DataGrid


I need a DataGrid with just a single column of double type to be able to add, edit and delete entries from a local list variable.

My list is defined as an observable collection:

public ObservableCollection<double> Values = 
    new ObservableCollection<double>() { 1.0, 20 };

How to I bind the list to a DataGrid without wrapping it by a class?


Solution

  • If you don't want to create a data model with named properties (to use column auto generation) you will need to explicitly define the column layout by setting the DataGrid.DataGridTextColumn:

    MainWindow.xaml

    <Window>
      <Window.DataContext>
        <ViewModel />
      </Window.DataContext>
    
      <DataGrid ItemsSource="{Binding Values}" IsReadOnly="True" >  
        <DataGrid.Columns>
          <DataGridTextColumn Header="Value"
                              Binding="{Binding}" />
        </DataGrid.Columns>
      </DataGrid>
    </Window>
    

    ViewModel.cs

    class ViewModel : INotifyPropertyChanged
    {
      private ObservableCollection<double> values;
      public ObservableCollection<double> Values
      {
        get => this.values;
        set
        {
          this.values = value;
          OnPropertyChanged();
        }
      }
    
      // Constructor
      public void ViewModel()
      {
        // Initialize the data binding source of the DataGrid
        this.Values = new ObservableCollection<double>() { 1.0, 20 };
      }
    
      public event PropertyChangedEventHandler PropertyChanged;
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    Remarks
    When binding the cell to the double values directly (or when using empty binding syntax in general e.g. {Binding} or {Binding Path=.}) BindingMode.TwoWay and therefore cell editing is not possible. This means BindingMode.TwoWay requires a property. Therefore to make cells editable the cell's binding source must expose the value via a property that is exposed by a wrapping type (data model or POCO).