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<Customer> _results = new
ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers {get { return _results; }}
private void LoadCustomers()
{
IList<Customer> 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