어제 동적으로 DataGrid에 항목을 추가하는 예제를 작성했는데요, 거기서는 INotifyCollectionChanged가 자체적으로 구현되어 있는 ObservableCollection 을 사용하였습니다.
그러나 이 ObservableCollection은 사용가능한 기능이 우리가 가장 많이 사용하는 List에 비해서는 제한적입니다. 예를 들어 Sort가 필요하다면 List를 사용해야 할 것입니다.
그래서, List가 제공하는 기능을 활용하면서 one-way 바인딩을 통한 동적인 DadaGrid 바운딩이 가능하도록 구현하려고 시도해 보았습니다. 완벽한 구현은 아니지만 참고할 만한 정도는 될것입니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Specialized;
namespace SilverlightTwoDatagrid2
{
public partial class Page : UserControl
{
MyList<string> list;
public Page()
{
InitializeComponent();
dgOld.ItemsSource = "One Two Three Four Five Six".Split();
btAdd.Click += new RoutedEventHandler(btAdd_Click);
list = new MyList<string>();
list.Add("Hello World!");
dgNew.ItemsSource = list;
}
void btAdd_Click(object sender, RoutedEventArgs e)
{
list.Add(dgOld.SelectedItem.ToString());
}
}
public class MyList<T> : List<T>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged
(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
public new void Add(T item)
{
base.Add(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs
(NotifyCollectionChangedAction.Reset));
// 정상적으로는 이벤트 발생시 Add Action을 전송해야 하는데,
// 위치조정이 어려워 Reset Action을 대신 전송했으니 차후에
// 실전 사용시는 적절히 수정해서 사용해야 할 필요가 있습니다.
// OnCollectionChanged((new NotifyCollectionChangedEventArgs
// (NotifyCollectionChangedAction.Add, o, 0));
}
public new void Remove(T item)
{
base.Remove(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs
(NotifyCollectionChangedAction.Reset));
//
// OnCollectionChanged(new NotifyCollectionChangedEventArgs
// (NotifyCollectionChangedAction.Remove, o, 0));
}
}
}
소스파일첨부:
SilverlightTwoDatagrid2.zip