Playing Chicken With Common Sense

Okay so the title makes no sense but that’s alright because I understand it and that’s all that matters.  haha Just kidding…  Take it easy…

Let’s say you have a WPF application with a DataGrid on it.  You also have a strongly typed list of objects – I.E. List<Person> which you would normally bind to your grid.  You might have been under the misconception that you can’t convert the List<Person> to a BindingListCollectionView.  I have searched google for answers and ran across people saying you can’t do that.

It is possible and I will show you how to make it happen.

Instead of setting the ItemsSource to List<Person>(…) you will instead convert the List<Person> to a BindingList<Person>; then you can assign the BindingList<Person> to a BindingListCollectionView(…).

Here is a short piece of code to illustrate.

   1: public partial class Window1 : Window
   2: {
   3:     private static IList<Person> MyFriends
   4:     {
   5:         get
   6:         {
   7:             var persons = new List<Person>
   8:                 {
   9:                     new Person { FirstName = "Jack", LastName = "Hill", Age = 30 },
  10:                     new Person { FirstName = "Jill", LastName = "Pale", Age = 25 },
  11:                     new Person { FirstName = "Evan", LastName = "Jacobs", Age = 21 }
  12:                 };
  13:  
  14:             return persons;
  15:         }
  16:     }
  17:  
  18:     public Window1()
  19:     {
  20:         InitializeComponent();
  21:  
  22:         var dataSource = new BindingListCollectionView(new BindingList<Person>(MyFriends));
  23:         dataSource.CurrentChanged += dataSource_CurrentChanged;
  24:         radGridView1.ItemsSource = dataSource;
  25:         listBox1.ItemsSource = dataSource;
  26:     }
  27:  
  28:     void dataSource_CurrentChanged(object sender, EventArgs e)
  29:     {
  30:         Person currentItem = ((BindingListCollectionView) sender).CurrentItem as Person;
  31:         System.Diagnostics.Debug.WriteLine(string.Format("Current Item changed {0}", currentItem.FirstName));
  32:     }
  33: }

 

It is sometimes quite difficult to find the help you need because your search keywords were not exactly what was on the web page but hopefully I have put enough keywords on this page to get you the answer you need and thus my reason for such a goofy title.

BindingListCollectionView Converter.7z (380.44 kb)

 

  • 1 Comments
  • E-mail
  • Kick it!
  • Shout it
  • Bookmark and Share

Comments

trackback DotNetShoutout    7/2/2009 10:26:53 AM #

wijix | Use a BindingListCollectionView from a BindingList from a List

Thank you for submitting this cool story - Trackback from DotNetShoutout

Control panel

RecentComments

Comment RSS