36

私はWPFを初めて使用し、DataGridsを使用しており、ItemsSourceプロパティがいつ変更されるかを知る必要があります。

たとえば、この命令が実行されると、イベントが発生する必要があります。

dataGrid.ItemsSource = table.DefaultView;

または、行が追加されたとき。

私はこのコードを使おうとしました:

CollectionView myCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(myGrid.Items);
((INotifyCollectionChanged)myCollectionView).CollectionChanged += new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged); 

ただし、このコードは、ユーザーがコレクションに新しい行を追加した場合にのみ機能します。したがって、コレクション全体が置き換えられたか、単一の行が追加されたために、ItemsSourceプロパティ全体が変更されたときに発生するイベントが必要です。

あなたが私を助けてくれることを願っています。前もって感謝します

4

3 に答える 3

70

ItemsSourceは依存関係プロパティであるため、プロパティが別のプロパティに変更されたときに通知を受け取るのは簡単です。次の代わりにではなく、持っているコードに加えてこれを使用することをお勧めします。

(または同様の)ではWindow.Loaded、次のようにサブスクライブできます。

var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(DataGrid));
if (dpd != null)
{
    dpd.AddValueChanged(myGrid, ThisIsCalledWhenPropertyIsChanged);
}

そして、変更ハンドラーがあります。

private void ThisIsCalledWhenPropertyIsChanged(object sender, EventArgs e)
{
}

ItemsSourceプロパティが設定されるたびに、ThisIsCalledWhenPropertyIsChangedメソッドが呼び出されます。

これは、変更について通知する必要がある依存関係プロパティに使用できます

于 2012-05-22T19:45:39.287 に答える
19

これは何か助けになりますか?

public class MyDataGrid : DataGrid
{
    protected override void OnItemsSourceChanged(
                                    IEnumerable oldValue, IEnumerable newValue)
    {
        base.OnItemsSourceChanged(oldValue, newValue);

        // do something here?
    }

    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);

        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                break;
            case NotifyCollectionChangedAction.Remove:
                break;
            case NotifyCollectionChangedAction.Replace:
                break;
            case NotifyCollectionChangedAction.Move:
                break;
            case NotifyCollectionChangedAction.Reset:
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
}
于 2012-05-22T19:52:00.157 に答える
-1

追加された新しい行を検出したい場合は、DataGridInitializingNewItemまたはAddingNewItemイベントを試すことができます。

InitializingNewItem利用方法 :

親のデータを含むDatagrid自動追加アイテム

于 2017-03-22T02:39:10.067 に答える