Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to bind a observable collection to a grid through xaml

collection is in cs file of xaml1 and grid in xaml2... how do i do it..
Posted

1 solution

You need to make the ObservableCollection available via a Public Property on xaml1. Then in xaml2 you need a reference to xaml1, you can do this by passing an instance of xaml1 in the constructor of xaml2. Then you can bind the DataGrid to the Collection. Here is a simple example( I used WPF but the methodology is the same for Silverlight)


C#
public partial class MainWindow: Window
   {
       private ObservableCollection<Person> people;
       public ObservableCollection<Person> People
       {
           get
           {
               return people;
           }
       }
       public MainWindow()
       {
           InitializeComponent();
           people = new ObservableCollection<Person>() {new Person("a"), new Person("b"), new Person("c"), new Person("d"), new Person("e") };
       }
       private void buttonClick(object sender, RoutedEventArgs e)
       {
           Window1 w1 = new Window1(this);
           w1.Show();
       }
   }
   public class Person
   {
       public string Name { get; set; }
       public Person(string name)
       {
           this.Name = name;
       }
   }


and this is how to bind in the second window

C#
public partial class Window1 : Window
   {
       public Window1(MainWindow mw)
       {
           InitializeComponent();
           dataGrid1.DataContext = mw.People;
           dataGrid1.DisplayMemberPath = "Name";
       }
   }


Hope this helps
 
Share this answer
 
Comments
Tarun.K.S 8-Jun-11 4:50am    
Comment from Ashakoti:
Thank u
I want to bind the collection in .cs to the grid through xaml.. not code behind.. Mine is a web application..

For ur ref..
.cs file of xaml2

SpaceList.Instance.SpacesList.AddRange ( _allAccountSpaces[_accountIdForServiceCall] );

xaml1

Grid ItemsSource={Binding SpacesList}
Mark Salsbery 9-Jun-11 1:41am    
What do you mean "Mine is a web application"? What does that have to do with having or not having code-behind? You do know that XAML produces code too, right? :)

Anyway, the same binding rules apply. You need an instance of the class containing the field or property you want to bind to. You can create that instance in code and perhaps use the DataContext property somewhere to make the instance visible to the XAML, or you can create a static instance in the XAML.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900