views:

416

answers:

3

Hello

I have little problem with databinding in my current project. I have an ObservableCollection I want to bind to an ListBox.

public ObservableCollection<GeoDataContainer> geoList = new ObservableCollection<GeoDataContainer>();

...later...

geoListBox.ItemsSource = geoList;

This code works fine. The Listbox has a datatemplate and everything looks perfect.

But I don't want to use C# code for binding. I want to make the binding in the XAML Code. I am searching for days but I don't get it. These are two lines C# code but to archive this in XAML it seems impossible without creating my own class for my collection or adding a DataProvider or resources or whatever.

Is there no easy way to do it?

+4  A: 

All you have to do is expose the collection and bind to it. For example, if you expose it as:

public ICollection<GeoDataContainer> GeoList
{
    get { return geoList; }
}

You will be able to bind to it as:

<ListBox ItemsSource="{Binding GeoList}"/>

The "trick" is to make sure that the DataContext of the ListBox is the class that exposes the GeoList property.

HTH, Kent

Kent Boogaart
A: 

Kent suggestion is the way to go...

On a further note, if you do not wish to set your DataContext to the list, you can also retrieve the property with an another form of binding:

Make sure your root control has a name, i.e. "Root"

{Binding ElementName=Root, Path=GeoList}
Arcturus
I must admit I don't get it to work.I tried all you suggestions and the program does compile. But all I get is a blank entry in my Listbox. I used ObservableCollection because every time I add an object the Listbox is refreshed. But it is not happening.
Holli
Make sure your control has a name, specified like so: x:Name="Root" in your xaml file...Also, please make sure that the Binding is not in a Template somehow, because you might need a RelativeSource binding to bind correctly to your data!
Arcturus
+1  A: 

Another good way would be instantiating geoList as a resource

<WindowResources>
  <l:GeoCollection x:Key="geoList"/>
</WindowResources>

Then you have

GeoCollection geoList = FindResource("geoList") as GeoCollection;

Of course, this is for cases when the data is related to the view only. If this is related to model or modelview, you use DataContext and bind to its properties.

Sergey Aldoukhov