我对我的数据网格如何更新感到困惑。
我有一个如下定义的数据网格:
<DataGrid ItemsSource="{Binding Customers}" Style="{StaticResource DataGridDemoRowStyle}" x:Name="grid"/>
c Customers
对象是在我的viewmodel中找到的ICollectionView。
在我的视图模型中,我像这样填充网格:
public ICollectionView Customers { get; private set; }
var _customers = new List<Customer>
{
new Customer
{
FirstName = "Christian",
LastName = "Moser",
Gender = Gender.Male,
WebSite = new Uri("http://www.wpftutorial.net"),
ReceiveNewsletter = true,
Image = "Images/christian.jpg"
},
new Customer
{
FirstName = "Peter",
LastName = "Meyer",
Gender = Gender.Male,
WebSite = new Uri("http://www.petermeyer.com"),
Image = "Images/peter.jpg"
},
new Customer
{
FirstName = "Lisa",
LastName = "Simpson",
Gender = Gender.Female,
WebSite = new Uri("http://www.thesimpsons.com"),
Image = "Images/lisa.jpg"
},
new Customer
{
FirstName = "Betty",
LastName = "Bossy",
Gender = Gender.Female,
WebSite = new Uri("http://www.bettybossy.ch"),
Image = "Images/betty.jpg"
},
};
Customers = CollectionViewSource.GetDefaultView(_customers);
这是按预期工作的。然后我决定尝试添加到集合中,假设网格不会更新,但它确实:
List<Customer> i = Customers.SourceCollection;
i.Add(new Customer() { FirstName = "Bobby" });
我的问题是,这是如何更新网格的?我没有在ICollectionView上调用Refresh
方法。我只能假设ICollectionView在某个时候调用了INotifyCollectionChanged事件。
我的模型确实实现了INotifyPropertyChanged,但是我没有看到这将如何更新网格以添加新项目,只更新当前项目。
答案 0 :(得分:0)
我已经测试了像你的样本,但是稍微修改了一下,并且所有工作都按预期工作 - DataGrid没有更新。代码如下:
public partial class MainWindow : Window
{
private ICollectionView customers;
public MainWindow()
{
var _customers = new List<Customer>
{
// Fill collection
};
customers = CollectionViewSource.GetDefaultView(_customers);
InitializeComponent();
DataContext = customers;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var c = new Customer { FirstName = "The new", LastName = "The added" };
// Note that cast is required, otherwise compilation error occurs.
List<Customer> i = this.customers.SourceCollection as List<Customer>;
i.Add(c);
}
}
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding}" />
<Button Content="Click me" Grid.Row="1" Click="Button_Click" />
</Grid>
目标.net框架是4.5,但我认为这不是那么重要。
这意味着你错过了细节。在您的方案中,您可以为CollectionChanged实例的ICollectionView事件添加事件处理程序,在这里您可以了解此类行为的根本原因。