Databinding using ObservableCollection<T>

Someone asked me today:
I have a text field and a drop down menu, based on the values of these 2 when i click on a button an api call is made to get the results. Now i want to display these results in a ListView using GridView. How can i use ObservableCollection to read the data when the search button is hit.

My Short Reply:

Creating an ObservableCollection is pretty straight forward.

1. For example say we have class Customer { id, name, address }

2. Now lets create a DataSrc that returns an ObservableCollection of Customer
public class CustomerDataSrc
{
 private ObservableCollection _results = new
ObservableCollection();
 public ObservableCollection Customers {get { return _results; }}
 private void LoadCustomers()
 {
   IList customers = YourDAL.FindAll();
   foreach (Customer customer in customers)
   {
     _results.Add(customer);
   }
 }
}

3. Declare an ObjectDataProvider in your XAML Page.Resources
<Page.Resources>
 <ObjectDataProvider x:Key="CustomerDataSrc"
                   d:IsDataSource="True"
                   ObjectType="{x:Type Client_DataSources:CustomerDataSrc}"/>
</Page.Resources>

4. Bind the ListView like this:
<ListView x:Name="dataGrid"
              ItemsSource="{Binding Path=Customers,
              Mode=Default,
              Source={StaticResource CustomerDataSrc}}">

5. In the code behind do this: (change according to the on button click event)

private void Page_Loaded(object sender, RoutedEventArgs e)
{
  ObjectDataProvider odp = this.FindResource("CustomerDataSrc") as ObjectDataProvider;
  _customerSrc = odp.ObjectInstance as CustomerDataSrc;
  _customerSrc.IsDesignTime = System.ComponentModel.DesignerProperties.GetIsInDesignMode(this);
  _customerSrc.LoadCustomers();
}

Hope this helps

This article is part of the GWB Archives. Original Author: Shahed Khan

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.