2012-05-22 8 views
25

WPF에서 새로 도입되었으며 DataGrids로 작업 중이므로 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은 종속성 속성이므로 속성을 다른 것으로 변경하면 알림을받을 정도로 쉽습니다. 당신은 당신의하지 않고, 가지고 코드 이외에이 사용하고자하는 것 :

에서 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 메서드가 호출됩니다.

변경 내용에 대한 알림을 받고 싶은 종속성 속성에이 값을 사용할 수 있습니다.

+3

매우 좋습니다! 정확히 내가 무엇을 찾고 있었는지. –

+0

표준 컨트롤을 상속하는 경우 멋진 컨트롤 동작을 만들 수 있습니다! – BendEg

+0

우수 인물. 내 시간을 절약 했어. :) – shanmugharaj

8

이 도움이 무엇입니까?

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(); 
     } 
    } 
} 
-1

당신은 데이터 그리드의 InitializingNewItem 또는 AddingNewItem 이벤트를 시도 할 수 있습니다 추가 된 새로운 열을 감지하는 wnat합니다.

InitializingNewItem 사용 :

Datagrid auto add item with data of parent

관련 문제