我對這種情況使用ObservableCollection。 實施例:
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" />