Blog Archive

Wednesday, May 21, 2008

Collection View


Data should be separated out from UI Elements for data binding purposes. In fact, Sorting, Grouping, selected changed event ( as in IBindingList) are better handled in View ( such as DataView and ListCollectionView). Here is a simple usage of Collection View in WPF:


public class Stock
{
public string Symbol { get; set; }
public double Price { get;set;}
public Stock(string s, double p)
{
this.Price = p;
this.Symbol = s;
}

public override string ToString()
{
return Symbol + " " + Price;
}
}

List<Stock> stocks = new List<Stock>();
stocks.Add(new Stock("YHOO", 27.90));
stocks.Add(new Stock("MSFT", 28.90));
stocks.Add(new Stock("GOOG", 179.40));
ListCollectionView cv = new ListCollectionView(stocks);
cv.SortDescriptions.Add(new SortDescription("Symbol", ListSortDirection.Ascending));
Binding b = new Binding();
b.Source = cv;
this.listBox1.SetBinding(ListBox.ItemsSourceProperty, b);


No comments: