Strange behavior when setting ItemsSource
I have a listbox (in a window) and I'm attempting to set the ItemSource to an Observable Collection. I have a window with a property defined (LayerCollection is an observable collection):
public class Window
{
...
private Map map;
public Map Map
{
get { return map; }
}
...
myListBox.ItemsSource = Map.LayerCollection;
This works!
But if I try to set ItemsSource in XAML it doesn't work:
<ListBox ItemsSource="{Binding Path=Map2D.LayerCollection}" ..... />
Try the following xaml code:
<ListBox ItesmSource="{Binding Path=Map.LayerCollection, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}"/>
It probably doesn't have any items when the binding takes place, as I am adding them dynamically in code. But does this matter, since it is, after all, a data binding that should update based on what's in the collection?
If the binding is done when Map is null or LayerCollection is null it won't bind to anything. You may want to either make map a dependency property or implement INotifyPropertyChange and trigger when you assign to the map field, same thing for the LayerCollection property.