WpfDatagrid Collectionviewsource clear

3.1k views Asked by At

I am using wpftoolkit datagrid control which was binding using collectionviewsource for records grouping. Whenever user trying to clear the form i need to clear the datagrid also. I tried to set datagrid itemsource to null but it works fine for clear functionality .if user trying to add any records to datagrid it's not loading.

So could any one please provide me a solution to clear the datagrid.

Thanks In Advance.

1

There are 1 answers

0
vortexwolf On

I use ObservableCollection for this type of situations. Example:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.items = new ObservableCollection<Item>(
            Enumerable.Range(0, 10).Select(i => new Item {Id = i, Title = "str " + i}));
        this.viewSource = new CollectionViewSource() { Source = this.items };

        dataGrid1.ItemsSource = this.viewSource.View;
    }

    private ObservableCollection<Item> items;
    private CollectionViewSource viewSource;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        items.Clear();
        //or
        //((ObservableCollection<Item>)viewSource.Source).Clear();
    }

    public class Item
    {
        public int Id { get; set; }
        public string Title { get; set; }
    } 
}

Xaml:

<Button HorizontalAlignment="Center" Content="Clear" Click="Button_Click"/>
<DataGrid AutoGenerateColumns="True" Name="dataGrid1" />