2013-04-30 3 views
0

다음과 같은 클래스가 있습니다. 아래 그림과 같이 내가 INotifyCollectionChanged가 UI를 업데이트하지 않습니다.

public class PersonCollection:IList<Person> 
{} 

간결

제거 한 모든 기능은 지금은 또 하나 개의 모델 클래스가 있습니다. AddValueCommand는 ICommand에서 파생 된 클래스이며 다시 생략합니다. 메인 창에서
public class DataContextClass:INotifyCollectionChanged 
{ 
    private PersonCollection personCollection = PersonCollection.GetInstance(); 

    public IList<Person> ListOfPerson 
    { 
     get 
     { 
      return personCollection; 
     }    
    } 

    public void AddPerson(Person person) 
    { 
     personCollection.Add(person); 
     OnCollectionChanged(NotifyCollectionChangedAction.Reset); 
    } 


    public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { }; 
    public void OnCollectionChanged(NotifyCollectionChangedAction action) 
    { 
     if (CollectionChanged != null) 
     { 
      CollectionChanged(this, new NotifyCollectionChangedEventArgs(action)); 
     } 
    }  

    ICommand addValueCommand; 

    public ICommand AddValueCommand 
    { 
     get 
     { 
      if (addValueCommand == null) 
      { 
       addValueCommand = new AddValueCommand(p => this.AddPerson(new Person { Name = "Ashish"})); 
      } 
      return addValueCommand;    
     } 
    } 
} 

나는

DataContextClass contextclass = new DataContextClass();   
this.DataContext = new DataContextClass(); 

아래 그림 그리고 내 UI가 함께 업데이트되지

<ListBox Margin="5,39,308,113" ItemsSource="{Binding Path=ListOfPerson}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBox Height="20" Text="{Binding Path=Name}"></TextBox> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
    <Button Content="Button" HorizontalAlignment="Left" Command="{Binding Path=AddValueCommand}" Margin="233,39,0,73" /> 

내 목록 상자 아래와 같이처럼 보이는 모델 내 UI를 결합하고 버튼이 클릭되었을 때의 새로운 값 내가 여기서 누락 된 것.

답변

8

INotifyCollectionChanged은 컬렉션 클래스에 의해 구현되어야합니다. 컬렉션에 컬렉션이 포함 된 클래스가 아닙니다.
DataContextClass에서 INotifyPropertyChanged을 제거하고 PersonCollection에 추가해야합니다. 대신 다음과 같이 당신의 PersonCollection 클래스를 IList 사용 ObservableCollection<T>를 사용하여 정의의

+0

Answers에 대해 고마워,하지만 여기에 내 PersonCollection을 변경하고 싶지 않다면 어떻게 될까? DataContextClass에서 변경 작업 만 수행하면 어떻게 할 수 있습니까? – Vikram

+1

@Vikram : 할 수 없습니다. WPF 엔진은 'ItemsSource'에 바인딩 된 속성에서 해당 인터페이스를 찾습니다. 데이터 컨텍스트에서 해당 인터페이스를 찾지 않습니다. –

8

:

public class PersonCollection : ObservableCollection<Person> 
{} 

당신은 WPF의 데이터 바인딩 시나리오에서 컬렉션을 변경 알림을 위해 특별히 설계 등에 대한 ObservableCollection<T> 클래스 here을 읽을 수 있습니다. 아래 MSDN의 정의에서 볼 수 있듯이

은 이미 WPF에서 ObservableCollection에 클래스의 사용에 도움을 INotifyCollectionChanged

public class ObservableCollection<T> : Collection<T>, 
    INotifyCollectionChanged, INotifyPropertyChanged 

더 많은 기사를 구현하는 다음과 같습니다 :

Create and Bind to an ObservableCollection
An introduction to ObservableCollection in Wpf
Databinding a ObservableCollection in MVVM

+0

답해 주셔서 감사합니다. 하지만 불행히도 PersonCollection에서 변경 작업을 수행 할 수 없습니다. – Vikram