Xavier
Xavier

Reputation: 359

Why my binding don't work on a ObservableCollection

Hello I am trying to bind a ItemsSource to a ObservableCollection. It seems the ObservableCollection is not seen by the IntelliSense event if the ObservableCollection is public.

Do I have the declare something in XAML to make it visible ? Like in Window.Ressources.

My XAML code

<Window x:Class="ItemsContainer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel Orientation="Horizontal">
        <ListBox ItemsSource="{Binding StringList}" />
    </StackPanel> </Window>

My C# code

using System.Collections.ObjectModel;
using System.Windows;

namespace ItemsContainer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private ObservableCollection<string> stringList = new ObservableCollection<string>();

        public ObservableCollection<string> StringList
        {
            get
            {
                return this.stringList;
            }
            set
            {
                this.stringList = value;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.stringList.Add("One");
            this.stringList.Add("Two");
            this.stringList.Add("Three");
            this.stringList.Add("Four");
            this.stringList.Add("Five");
            this.stringList.Add("Six");
        }
    }
}

To the best of my knowledge that binding should bind to the property StringList of the current DataContext, which is MainWindow.

Thanks for any pointer.

Edit:

This worked for me in XAML

<Window x:Class="ItemsContainer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel Orientation="Horizontal">
        <ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=StringList}" />
    </StackPanel>
</Window>

Upvotes: 0

Views: 281

Answers (1)

CodeNaked
CodeNaked

Reputation: 41393

The DataContext does not default to the MainWindow, you'd have to explicitly set that. Like so:

public MainWindow() {
    InitializeComponent();
    this.stringList.Add("One");
    this.stringList.Add("Two");
    this.stringList.Add("Three");
    this.stringList.Add("Four");
    this.stringList.Add("Five");
    this.stringList.Add("Six");
    this.DataContext = this;
}

Upvotes: 3

Related Questions