Reputation: 75
How do I bind a ObservableCollection<updateData>
updateCollection
to a DataGrid
? I tried several solution but none seem to work as rows are added to the collection but don't show up on the grid. I tried to bind to the class only, then I can add rows but when I try to edit them i get the error 'EditItem' is not allowed for this view
. The grid is the following
<DataGrid Name="dgv" Grid.ColumnSpan="7" AutoGenerateColumns="False" ItemsSource="{Binding updateCollection}" IsSynchronizedWithCurrentItem="True" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Hour" SelectedValueBinding="{Binding Active}" ItemsSource="{StaticResource hoursList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
<DataGridComboBoxColumn Header="Origin" SelectedValueBinding="{Binding Origin}" ItemsSource="{StaticResource originList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
<DataGridTextColumn Header="P" Binding="{Binding Path=Price}"/>
<DataGridTextColumn Header="Q" Binding="{Binding Path=Quantity}"/>
</DataGrid.Columns>
And the updateData
class is the following:
public class updateData
{
public string Price { get; set; }
public string Quantity { get; set; }
public string Origin { get; set; }
public string Hour { get; set; }
}
Upvotes: 1
Views: 7642
Reputation: 1864
What you did looks correct, but if you miss one single thing, the DataContext
… nothing will work.
Here an example just for you:
This is your Model:
public class updateData
{
public string Price { get; set; }
public string Quantity { get; set; }
public string Origin { get; set; }
public string Hour { get; set; }
}
Note that, if you want to tell to your view that something has changed, you have to implement the INotifyPropertyChanged
interface.
This is your ViewModel:
public class updateDataVm
{
public ObservableCollection<updateData> updateCollection { get; set; }
public updateDataVm()
{
updateCollection = new ObservableCollection<updateData>();
}
}
And finally here is your View (note that i have changed ItemsSource
to ItemsSource="{Binding}"
):
<Grid>
<DataGrid Name="dgv" Grid.ColumnSpan="7" AutoGenerateColumns="False" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Hour" SelectedValueBinding="{Binding Active}" ItemsSource="{StaticResource hoursList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
<DataGridComboBoxColumn Header="Origin" SelectedValueBinding="{Binding Origin}" ItemsSource="{StaticResource originList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
<DataGridTextColumn Header="P" Binding="{Binding Path=Price}"/>
<DataGridTextColumn Header="Q" Binding="{Binding Path=Quantity}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
In your window (or generally control):
public partial class MainWindow : Window
{
public updateDataVm collection;
public MainWindow()
{
InitializeComponent();
collection = new updateDataVm();
DataContext = collection;
}
}
Upvotes: 6