Reputation: 129
How do I insert a Row in a desired position in Wpf DataGrid?
I have tried:
GridCollection.Insert(2, (new ColumnCollection()))
In order to insert it at the 3rd index. Where GridCollection Is the ItemSource
of the DataGrid
. But it's adding row on the last of the Grid.
Upvotes: 1
Views: 1596
Reputation: 69959
In WPF, we generally work with data rather than UI elements. Therefore, to do this in data, we'd just need to do this:
DataBoundCollection.Insert(2, newItem);
If you have correctly implemented the INotifyPropertyChanged
Interface in your view model or code behind (or used a DependencyProperty
in a UserControl
or Window
code behind) and data bound a collection of items to your DataGrid.ItemsSource
, then the above code will result in a new item being added into the DataGrid
in the third from top position:
<DataGrid ItemsSource="{Binding DataBoundCollection}" ... />
UPDATE >>>
I have no idea what you're doing, but I'm guessing that you have over complicated the situation. Ignore your current code and put this into a new project and then you will see that it works perfectly:
The XAML:
<DataGrid ItemsSource="{Binding Numbers}" MouseDoubleClick="DataGrid_MouseDoubleClick">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding}" />
</DataGrid.Columns>
</DataGrid>
The code behind:
private ObservableCollection<int> numbers = new ObservableCollection<int>();
public ObservableCollection<int> Numbers
{
get { return numbers; }
set { numbers = value; NotifyPropertyChanged("Numbers"); }
}
...
private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Numbers.Insert(2, 10);
}
In the constructor:
Numbers = new ObservableCollection<int>() { 1, 2, 3, 4, 5 };
Now when you double click on the DataGrid
, you'll see new rows being added at position 3, not at the beginning or end.
Upvotes: 1