2012-05-22 43 views
25

私はWPFで新しく、DataGridで作業しています。プロパティItemsSourceがいつ変更されるかを知る必要があります。DataGrid.ItemsSourceが変更されたときにイベントを発生させる方法

dataGrid.ItemsSource = table.DefaultView; 

するか、行が追加されたとき:

例えば、私は、この命令が実行されるときにイベントを提起しなければならないことが必要であろう。

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

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

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

私があなたを助けてくれることを願っています。事前にありがとう

+0

あなたはrow_Createdイベントで見たことがありますか? – Limey

答えて

52

ItemsSourceは依存関係のプロパティであるため、プロパティが他のものに変更されたときに通知するのは簡単です。

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

と変更ハンドラがあります:あなたがそうのように購読することができ

Window.Loaded

(または類似):あなたがいない代わりに、あなたが持っているコードに加えて、これを使用したい

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

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

これはの任意の依存プロパティに対して変更を通知したい場合に使用できます。

+3

非常に良い!まさに私が探していたもの。 –

+0

標準のコントロールを継承している場合、素晴らしいコントロールの動作を作成できます! – BendEg

+0

優秀な男。私の時間を節約しました。 :) – shanmugharaj

8

これは役に立ちましたか?追加した新しい行を検出するwnat場合

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(); 
     } 
    } 
} 
関連する問題