问题描述
我在WPF新的,但我是DataGrid的工作,我需要知道什么时候该属性的ItemsSource被改变。
I am new in WPF, and I am working with DataGrids and I need to know when the property ItemsSource is changed.
例如,我需要在执行该指令时,一个事件有加:
For example, I would need that when this instruction is executed an event has to raise:
dataGrid.ItemsSource = table.DefaultView;
或当行添加。
我试图用这个code:
I have tried to use this code:
CollectionView myCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(myGrid.Items);
((INotifyCollectionChanged)myCollectionView).CollectionChanged += new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged);
但是,只有当用户添加一个新行到集合此code工作。因此,我需要当整个ItemsSource属性有任何变化,或者是因为整个集合被替换或者因为单行补充的是,升高一个事件。
But this code works only when the user adds a new row to the collection. Therefore I need a event that be raised when the entire ItemsSource property has any change, either because the entire collection is replaced or because a single row is added.
我希望你能帮助我。谢谢你在前进
I hope you can help me. Thank you in advance
推荐答案
的ItemsSource
是一个依赖属性,所以它很容易被通知时,属性更改的东西其他。你想除了code,你有不是代替,使用这样的:
ItemsSource
is a dependency property, so it's easy enough to be notified when the property is changed to something else. You would want to use this in addition to code that you have, not instead of:
在 Window.Loaded
(或类似),您可以订阅像这样:
In Window.Loaded
(or similar) you can subscribe like so:
var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(DataGrid));
if (dpd != null)
{
dpd.AddValueChanged(myGrid, ThisIsCalledWhenPropertyIsChanged);
}
和有变化的处理程序:
private void ThisIsCalledWhenPropertyIsChanged(object sender, EventArgs e)
{
}
每当的ItemsSource
属性设置,在 ThisIsCalledWhenPropertyIsChanged
方法被调用。
Whenever the ItemsSource
Property is set, the ThisIsCalledWhenPropertyIsChanged
method is called.
您可以使用它进行的任何的你想依赖属性被通知的变化。
You can use this for any dependency property you want to be notified about changes.
这篇关于如何当DataGrid.ItemsSource改变引发一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!